Sql 雄辩的2左连接查询

Sql 雄辩的2左连接查询,sql,laravel,join,eloquent,Sql,Laravel,Join,Eloquent,我想使用Laravel雄辩的查询生成器执行以下查询: SELECT a.*, b.day, c.sex FROM hours as a left join reserves as b on a.id = b.hour_id and b.day = '2015-12-12' left join doctors as c on a.doctor_id = c.id where a.doctor_id = 1; 我尝试了以下方法: Hour::leftJoin('reserves', functio

我想使用Laravel雄辩的查询生成器执行以下查询:

SELECT a.*, b.day, c.sex FROM hours as a
left join reserves as b
on a.id = b.hour_id and b.day = '2015-12-12'
left join doctors as c
on a.doctor_id = c.id
where a.doctor_id = 1;
我尝试了以下方法:

Hour::leftJoin('reserves', function($join) {
    $join->on('hours.id' , '=' , 'reserves.hour_id')
        ->where('reserves.day' , '=' , '2015-12-12');
})
->leftJoin('doctors', function($join) {
    $join->on('hours.doctor_id', '=', 'doctors.id'); 
})
->where('hours.doctor_id', '=', $doctorId)
->get();

不幸的是,我没有得到相同的结果。

一切看起来都很好,但是您在
小时后错过了选择列::
您应该添加:

select('hours.*'.'reserves.day','doctors.sex')->
您还可以简化第二个连接并使用别名,因此最终代码可以如下所示:

Hour::select('hours.*'.'reserves.day','doctors.sex')
     ->from('hours AS a')
     ->leftJoin('reserves AS b', function($join) {
         $join->on('a.id' , '=' , 'b.hour_id')
        ->where('b.day' , '2015-12-12');
     })
    ->leftJoin('doctors AS c', 'a.doctor_id', '=', 'c.id')
    ->where('a.doctor_id', $doctorId)
    ->get();
当然,作为
$doctorId
您应该设置
1
以获得完全相同的结果

您可以使用DB::raw:

Hour::select(DB::raw('hours.*'),reserves.day, c.doctors)
->leftJoin('reserves',DB::raw("hours.id = reserves.hour_id AND reserves.day='2015-12-12'")  ,DB::raw(''), DB::raw(''))
->leftJoin('doctors','hours.doctor_id', '=', 'doctors.id')
->where('hours.doctor_id', '=', $doctorId)
->get()
2个空DB::raw是因为leftJoin需要4个参数
(表、列A、运算符、列B)