【问题标题】:Eloquent 2 left join queryEloquent 2 左连接查询
【发布时间】:2023-03-10 12:13:01
【问题描述】:

我想使用 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();

很遗憾,我没有得到相同的结果。

【问题讨论】:

    标签: sql laravel join eloquent


    【解决方案1】:

    一切看起来都很好,但是你错过了选择列,在 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 以获得完全相同的结果

    【讨论】:

      【解决方案2】:

      你可以使用 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)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-04-17
        • 2021-08-10
        • 1970-01-01
        • 1970-01-01
        • 2021-12-25
        • 2017-06-30
        • 2017-12-09
        • 1970-01-01
        相关资源
        最近更新 更多