如何在左侧外部联接的Laravel中使用select作为第二个条件

时间:2019-02-04 03:08:47

标签: mysql laravel

我正在尝试将此mysql块转换为laravel sql,但无论如何都无法成功

select tt.id
     , tt.date
     , m1.date
     , m2.date
     , m1.userid
     , m2.userid 
  from tbltickets tt 
  join tblticketreplies m1 
    on tt.id = m1.tid 
  left
  join tblticketreplies m2 
    on m1.tid = m2.tid 
   and m2.date =
     (SELECT min(m3.date) 
       FROM tblticketreplies m3 
      WHERE m3.date > m1.date 
        and m3.tid=m1.tid) 
 where tt.date > NOW() - INTERVAL 1 MONTH;

Laravel块:

        $rows = DB::table('tbltickets')
        ->join('tblticketreplies as m1', 'tbltickets.id', '=', 'm1.tid')
        ->leftJoin("tblticketreplies as m2", function($join) {
            $join->on('m2.tid', '=', 'm1.tid');
            $join->on('m2.date',"=",DB::raw("SELECT min(m3.date) FROM tblticketreplies m3 WHERE m3.date > m1.date and m3.tid=m1.tid"));
        })
        ->select('tt.id as id,tt.date as first,m1.date as second,m2.date as third ,m1.userid as fid,m2.userid as sid')
        ->get();

任何机构都知道如何在外部联接中使用select还是可以做到这一点?

1 个答案:

答案 0 :(得分:0)

您尚未将别名添加到tbltickets(tt)中,并且在select中使用了它,然后在select()中使用了它,现在您只需要传递多个参数即可,只是它的一个长字符串。

<?php
 $rows = DB::table('tbltickets as tt')
        ->join('tblticketreplies as m1', 'tbltickets.id', '=', 'm1.tid')
        ->leftJoin("tblticketreplies as m2", function($join) {
            $join->on('m2.tid', '=', 'm1.tid');
            $join->on('m2.date',"=", DB::raw("SELECT min(m3.date) FROM tblticketreplies m3 WHERE m3.date > m1.date and m3.tid=m1.tid"));
        })
        ->select(
            'tt.id as id', 
            DB::raw('tt.date as first'),
            DB::raw('m1.date as second'),
            DB::raw('m2.date as third'),
            DB::raw('m1.userid as fid'),
            DB::raw('m2.userid as sid')
        )
        ->get();