带有联接的Laravel查询生成器

时间:2018-07-12 22:26:48

标签: php laravel-5

我在将原始sql查询转换为laravel查询生成器时受阻。有人可以帮我解决这个问题吗?

select p.name, p.`type`, p.`status`, p.state, ps1.* from pos_session ps1 right join pos p on ps1.pos_id = p.id where ps1.id = (select max(ps0.id) from pos_session ps0 where ps0.pos_id = ps1.pos_id) or p.site_id = '2' order by ps1.pos_id;

1 个答案:

答案 0 :(得分:0)

尝试以下查询:

 DB::table('pos_session AS ps1')
        ->select('p.name','p.type','p.status','p.state','ps1.*')
        ->rightJoin('pos AS p','ps1.pos_id','=','p.id')
        ->where('ps1.id','=',function($query){
            $query->select(DB::raw('MAX(ps0.id)'))
                ->from('pos_session AS ps0')
                ->where('ps0.pos_id','=','ps1.pos_id');
        })
        ->orWhere('p.site_id','=',2)
        ->orderBy('ps1.pos_id')
        ->get();

可以实现通过加入的结果,以及:

DB::table('pos_session AS ps1')
            ->select('p.name','p.type','p.status','p.state','ps1.*')
            ->rightJoin('pos AS p','ps1.pos_id','=','p.id')
            ->join('pos_session AS ps0', 'ps0.pos_id', '=', 'ps1.pos_id')
            ->where('ps1.id','=',DB::raw('MAX(ps0.id)'))
            ->orWhere('p.site_id','=',2)
            ->orderBy('ps1.pos_id')
            ->get();

希望对您有所帮助:)