2015-12-29 35 views
0

我想使用Laravel雄辩的查询生成器来执行以下查询:雄辩2左连接查询

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

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

回答

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

0

您可以使用DB :: [R AW:

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 ::原料是因为leftJoin期望4个参数(table,columnA,operator,columnB)