Eloquent 2左连接查询

时间:2015-12-29 21:22:03

标签: sql laravel join eloquent

我想使用Laravel的eloquent查询构建器执行以下查询:

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();

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

2 个答案:

答案 0 :(得分:0)

一切看起来都不错,但在Hour::添加后,您错过了选择列:

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以获得完全相同的结果

答案 1 :(得分:0)

你可以使用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个参数(table,columnA,operator,columnB)