duandai7601 2016-03-18 02:03
浏览 59
已采纳

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

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

id, sender_id, message, receiver_id, created_at, updated_at

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

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

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.

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

$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);
  • 写回答

2条回答 默认 最新

  • douyi6922 2016-03-18 02:07
    关注

    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');
                })
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试