Laravel - 用 OR 运算符连接 2 个表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36074866/
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 13:25:57  来源:igfitidea点击:

Laravel - joining 2 tables with OR operator

phpmysqllaravellaravel-5

提问by KennethC

I have a table called messages, and it's columns are

我有一个名为messages的表,它的列是

id, sender_id, message, receiver_id, created_at, updated_at

And the other table is called users, and it's columns are

另一个表称为users,它的列是

id, firstname, lastname, email, password, created_at,updated_at

I want to get all the messages from all the users, so I'm joining the messages.sender_id and messages.receiver_id with users.id

我想从所有用户那里获取所有消息,所以我加入了messages.sender_id 和 messages.receiver_id 与 users.id

However I don't know how to use "OR" operator while joining in laravel here's my raw query that gives me the desired output.

但是,我不知道如何在加入 laravel 时使用“OR”运算符,这是我的原始查询,它为我提供了所需的输出。

SELECT messages.*,users.* FROM messages JOIN users ON users.id = messages.sender_id 
OR users.id = messages.receiver_id GROUP BY messages.id

Here's the laravel query that I tried

这是我尝试过的 Laravel 查询

$get_messages = DB::table('messages')
            ->where('messages.sender_id',$user_id)
            ->leftjoin('users', function($join){
                $join->on('users.id','=','messages.sender_id'); // i want to join the users table with either of these columns
                $join->on('users.id','=','messages.receiver_id');
            })
            ->orwhere('messages.sender_id',$partner_id)
            ->where('messages.receiver_id',$user_id)
            ->orwhere('messages.receiver_id',$partner_id)
            ->groupby('messages.id')
            ->get();

print_r($get_messages);

回答by aadarshsg

Try this.

尝试这个。

            ->leftjoin('users', function($join){
                $join->on('users.id','=','messages.sender_id'); // i want to join the users table with either of these columns
                $join->orOn('users.id','=','messages.receiver_id');
            })

回答by Haseena P A

YOu can also use the direct query

你也可以使用直接查询

$results = DB::select( DB::raw("SELECT messages.*,users.* FROM messages JOIN users ON users.id = messages.sender_id 
OR users.id = messages.receiver_id GROUP BY messages.id") );