laravel 如何从表中获取最后一条记录

bhmjp9jg  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(194)

enter image description here
我如何获取这些最新的记录与原始SQL语法
我知道如何让它通过雄辩的hasOne关系,但我需要做的是从加入

`发布

  • id;
  • return(");
  • string(“”);

历史记录

  • id;
  • foreignId('post_id');
  • “);
  • date('检查日期');`
icnyk63a

icnyk63a1#

例如,我们有用户和答案表。用户可以回答许多答案。我们需要拉与每个用户相关联的最新答案。$query =

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

字符串
参考:Laravel leftJoin only last record of right table

lnlaulya

lnlaulya2#

如果你想在Laravel中使用原始SQL查询而不是模型,你可以这样做。

$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
'));

字符串

相关问题