我该如何使用Laravel雄辩地编写此原始mysql左联接查询?

时间:2019-01-17 08:45:05

标签: mysql laravel eloquent left-join

我正在将Web应用程序转换为Laravel框架,但是在尝试以雄辩的Laravel语言编写特定的原始SQL查询时遇到了一个特定的问题。

以下是查询:

到目前为止,我已经尝试过:

$cp = DB::table('career_progression')
->select('staff_id', DB::raw('MAX(cpEffectiveDate) as max_date'))
->groupBy('staff_id');

$staffs = DB::table('staff')
        ->leftJoinSub($cp, 'cp', function ($join) {
             $join->on('staff.id', '=', 'cp.staff_id');
        })
->select(DB::raw('staff.firstname, staff.middlename, staff.lastname, staff.state, staff.lga, cp.cpEffectiveDate, cp.designation, cp.grade, 
        cp.step'));

这是我想要实现的:

SELECT s.firstname, s.middlename, s.lastname, s.state, s.lga, cp.cpEffectiveDate,cp.designation, cp.grade, cp.step FROM staff s LEFT JOIN career_progression cp ON cp.staff_id = s.id JOIN (SELECT a.staff_id, MAX(a.cpEffectiveDate) AS max_date FROM career_progression a GROUP BY a.staff_id) x ON x.staff_id = cp.staff_id AND x.max_date = cp.cpEffectiveDate

非常感谢您的任何提示/帮助。

0 个答案:

没有答案