Laravel / Model / Get latest record using join query
Get Latest Record using join query
-
STEP
Solution 1: Subquery in where
$query = Article::select('articles.*', 'comments.comment as article_comment') ->leftJoin('comments', function($query) { $query->on('comments.article_id','=','articles.id') ->whereRaw('comments.id IN (select MAX(a2.id) from comments as a2 join articles as u2 on u2.id = a2.article_id group by u2.id)'); }) ->get() It is not good if there are large number of records Solution 2: subquery in join
select * from gymdetails as g left join (SELECT gymId, max(subscriptionExpiryDate) as subscriptionExpiryDate FROM gympayments group by gymId ) as p on g.id=p.gymId order by p.subscriptionExpiryDate DESC $data['listData']=Gym::leftJoin( DB::raw(" (SELECT gymId, max(subscriptionExpiryDate) as subscriptionExpiryDate FROM `gympayments` group by `gymId` ) as p"), function($join){ $join->on("GymDetails.id","=","p.gymId"); } ) ->orderBy('p.subscriptionExpiryDate',$orderBy) ->paginate($pageLimit);