我真的需要帮助来解决我遇到的这个大问题。 我有树表:
公司:
id | owner_id | name | address
-------------------------------------
1 | 5 | Google | 25 St RD
2 | 5 | Yahoo | 36 Ave St
3 | 11 |Microsoft| 1 Ave St
4 | 5 | Amazon | 25 St NE
用户:
id | name | email | type
-------------------------------------
3 | Daniel | dn@gmail.com | customers
4 | Dave | vd@gmail.com | user
5 | Nancy | ncn@gmail.com | admin
6 | Robert | rb@gmail.com | user
用户公司
id | user_id |parent_id| company_id
-------------------------------------
1 | 3 | 5 | 2
2 | 3 | 5 | 2
3 | 11 | 5 | 3
4 | 3 | 6 | 1
问题一:我需要返回与company_id 2关联的所有用户 这是我的代码,但它没有返回正确的数据。
$CompanyList = DB::table('users')
->leftJoin('user_companies', 'users.id', '=', 'user_companies.parent_id')
->join('companies', 'users.id', '=', 'companies.user_id')->where('company_id', '=', 5)
->get(['users.name', 'users.email', 'user_companies.user_id']);
Note: parent_id is the id of who created the company record. I use it somewhere else.
问题二: 我的 user_id 为 5,我需要返回与 user_id 5 关联的所有公司。 我尝试使用相同的代码但没有成功。
任何帮助将不胜感激。
最佳答案
首先,您没有使用 Laravel 的 Eloquent 关系,这只是老式的 MySQL 关系。
其次,我不明白您在 user_companies 中的parent_id。如果一家公司有母公司,您将在公司表中将其设置为列,而不是在关系表中。
并且您的关系表“user_companies”没有唯一键,因此前两个结果具有相同的结果。
在创建数据库表之前,请确保规范化正常,然后阅读 Laravel 的文档:https://laravel.com/docs/5.3/eloquent-relationships#many-to-many
关于php - Laravel,Eloquent 上的三表关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39638917/