php - Laravel,Eloquent 上的三表关系

标签 php mysql postgresql laravel-5

我真的需要帮助来解决我遇到的这个大问题。 我有树表:

公司:

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/

相关文章:

php - 使用 PHP 在 WordPress 中设置页面标题

php - Symfony 使用 Swift Mailer 和 o2switch 发送电子邮件

postgresql - 在不使用 CTE 的情况下,是否有此查询的逻辑等效且有效的版本?

sql - 带有选择和值的 Postgres 插入

php - 可以使用 HipHop PHP 构建 php 扩展吗?

php - 我想打印带参数的 PHP 查询

mysql - 数据库中的 GMT 时间

php - MySQL加入多个映射表

php - 对所有商品价格求和并将它们乘以 laravel 中的数据透视表

postgresql - 使用初始模式构建 postgres docker 容器