Users::select('users.id', 'users.user_name','answers.created_at as last_activity_date')
->leftJoin('answers', function($query)
{
$query->on('users.id','=','answers.user_id')
->whereRaw('answers.id IN (select MAX(a2.id) from answers as a2 join users as u2 on u2.id = a2.user_id group by u2.id)');
})->where('users.role_type_id', Users::STUDENT_ROLE_TYPE)->get();
$results = DB::select(DB::raw('
SELECT p.id as post_id, p.no, p.division, h.id as history_id, h.content, h.inspection_date
FROM posts p
JOIN histories h ON p.id = h.post_id
JOIN (
SELECT post_id, MAX(inspection_date) as max_inspection_date
FROM histories
GROUP BY post_id
) latest_histories ON h.post_id = latest_histories.post_id AND h.inspection_date = latest_histories.max_inspection_date
'));
2条答案
按热度按时间icnyk63a1#
例如,我们有用户和答案表。用户可以回答许多答案。我们需要拉与每个用户相关联的最新答案。$query =
字符串
参考:Laravel leftJoin only last record of right table。
lnlaulya2#
如果你想在Laravel中使用原始SQL查询而不是模型,你可以这样做。
字符串