Php Laravel 5.6雄辩的ORM何处连接表

Php Laravel 5.6雄辩的ORM何处连接表,php,mysql,laravel,laravel-5,mariadb,Php,Mysql,Laravel,Laravel 5,Mariadb,我正在处理雄辩的ORM集合和查询生成器。我试图弄清楚如何在集合中加入并使用“where”,就像在查询生成器中一样 例如,我有以下表格: 用户: ID | Name | Last name ------------------------- 1 | Martin | Fernandez 2 | Some | User ID | Nick | User_ID | Active ---------------------------------- 1 | Tinc

我正在处理雄辩的ORM集合和查询生成器。我试图弄清楚如何在集合中加入并使用“where”,就像在查询生成器中一样

例如,我有以下表格:

用户

ID  |  Name  |  Last name
-------------------------
 1  | Martin | Fernandez
 2  | Some   | User
ID  |  Nick  |  User_ID  |  Active
----------------------------------
 1  | Tincho | 1         |  1
ID  | Name   | User_ID   |  Active
----------------------------------
 1  | Maramal| 1         |  0
 2  | Some   | 2         |  1
人员

ID  |  Name  |  Last name
-------------------------
 1  | Martin | Fernandez
 2  | Some   | User
ID  |  Nick  |  User_ID  |  Active
----------------------------------
 1  | Tincho | 1         |  1
ID  | Name   | User_ID   |  Active
----------------------------------
 1  | Maramal| 1         |  0
 2  | Some   | 2         |  1
公司

ID  |  Name  |  Last name
-------------------------
 1  | Martin | Fernandez
 2  | Some   | User
ID  |  Nick  |  User_ID  |  Active
----------------------------------
 1  | Tincho | 1         |  1
ID  | Name   | User_ID   |  Active
----------------------------------
 1  | Maramal| 1         |  0
 2  | Some   | 2         |  1
这是一个例子,我正在处理的表每个都有30多列。我想选择所有活动的用户

通常我会执行如下查询:

SELECT *
FROM users
LEFT JOIN persons ON users.id = persons.user_id
LEFT join companies ON users.id = companies.user_id
WHERE persons.active = 1
OR companies.active = 1
可以转换为Laravel查询生成器,如:

DB::table('users')
   ->leftJoin('persons', 'users.id', '=', 'persons.user_id')
   ->leftJoin('companies', 'users.id', '=', 'companies.user_id')
   ->where('persons.active', 1)
   ->orWhere('companies.active', 1)
   ->get(); 
但我想使用的是Laravel雄辩的ORM集合,到目前为止,我正在做以下工作:

$users= User::orderBy('id',' desc')->get();

foreach($users as $k => $user) {
    if($user->company && !$user->company->active || $user->person && !$user->person->active) {
        unset($users[$k]);
    }
    ... and here a lot of validations and unsets ...
 }
但我知道在这一点上,我已经抓住了所有的用户,而不是那些活跃的用户

如何在集合中实现查询生成器的功能?提前感谢。

这应该可以做到:

$users = User::whereHas('companies', function($q) {
    $q->where('active', true);
})->orWhereHas('persons', function($q) {
    $q->where('active', true);
})->with(['companies', 'persons'])->orderBy('id', 'desc')->get();
这应该做到:

$users = User::whereHas('companies', function($q) {
    $q->where('active', true);
})->orWhereHas('persons', function($q) {
    $q->where('active', true);
})->with(['companies', 'persons'])->orderBy('id', 'desc')->get();

我完全忘了这件事。非常感谢。只是一个注释,其中,
whereHas('companys')
companys是模型的名称,而不是表的名称。它实际上是关系函数的名称。我完全忘记了这一点。谢谢!只是一个注释,where
whereHas('companys'
companys是模型的名称,而不是表的名称。它实际上是关系函数的名称