Laravel 5.6 Eloquent ORM where join table

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49017762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:27:15  来源:igfitidea点击:

Laravel 5.6 Eloquent ORM where join table

phpmysqllaravellaravel-5mariadb

提问by Maramal

I am dealing with Eloquent ORM collections and query builders. I am trying to figure out how to join and use "where" in a collection, like in query builder.

我正在处理 Eloquent ORM 集合和查询构建器。我试图弄清楚如何在集合中加入和使用“where”,就像在查询构建器中一样。

For example, I have the following tables:

例如,我有以下表格:

Users:

用户

ID  |  Name  |  Last name
-------------------------
 1  | Martin | Fernandez
 2  | Some   | User

Persons:

人员

ID  |  Nick  |  User_ID  |  Active
----------------------------------
 1  | Tincho | 1         |  1

Companies:

公司

ID  | Name   | User_ID   |  Active
----------------------------------
 1  | Maramal| 1         |  0
 2  | Some   | 2         |  1

This is an example, the tables I am working on have more than 30 columns each one. I want to select all the user that are active.

这是一个示例,我正在处理的表每个都有 30 多列。我想选择所有活动的用户。

Usually I would do a query like:

通常我会做这样的查询:

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

That can be translated to Laravel Query Builder like:

这可以转换为 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(); 

But what I want to use is a Laravel Eloquent ORM Collection, until now I am doing the following:

但我想使用的是 Laravel Eloquent 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 ...
 }

But I know that at this point, I already grabbed allthe users instead those who are active.

但我知道,在这一点上,我已经抓住了所有用户,而不是那些活跃的用户。

How would I achieve what I did with query builder within a collection? Thanks in advance.

我将如何实现我在集合中使用查询构建器所做的事情?提前致谢。

回答by Paras

This should do it:

这应该这样做:

$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();