Laravel eloquent selecting most recent row from joined table

前端 未结 2 769
我在风中等你
我在风中等你 2021-01-12 07:45

I have two tables, Project and Projectnote

There is a one to many relationship between project and projectnote.

I want to be able to list my projects and sel

2条回答
  •  余生分开走
    2021-01-12 08:06

    You can join the table on the latest value:

    ->join('t1', function($join) {
            $join->on('t1.t2_id', '=', 't2.id')
                 ->on('t1.id', '=', DB::raw("(select max(id) from t1 WHERE t1.t2_id = t2.id)"));
    

    If you also want to join where t1 does not have a value, use a leftJoin. In your case this would look like this:

    $projects = Project::leftJoin('projectnotes', function($join) { 
            $join->on('projectnotes.project_id', '=', 'projects.id')
                 ->on('projectnotes.id', '=', DB::raw("(SELECT max(id) from projectnotes WHERE projectnotes.project_id = projects.id)")); 
            })
            ->select(array('projects.*', 'projectnotes.note as note'))
    

提交回复
热议问题