Laravel Eloquent JOIN AND SELECT MAX ROW

By Phạm Đình Hậu | Laravel

Apr 05

\DB::table(‘table1 AS t1’)

->leftJoin(\DB::raw(‘(SELECT * FROM table2 A WHERE id = (SELECT MAX(id) FROM table2 B WHERE A.id=B.id)) AS t2’), function($join) {

$join->on(‘t1.id’, ‘=’, ‘t2.id’);

})->get();

===

\DB::table(‘table1 AS t1’)

->leftJoin(\DB::raw(‘(SELECT MAX(id), col1, col2 FROM table2 GROUP BY col1, col2) as t2’), function($join) {

$join->on(‘t1.id’, ‘=’, ‘t2.id’);

})->get();

 

About the Author