Home > Software design >  Group by and get latest record of group
Group by and get latest record of group

Time:12-05

I am trying to group my Swipes by user_id, then I only need the latest (by created_at) Swipe per user_id. So at the end I would like to have only latest Swipes (Collection) by user_id with no duplicates.

How is this possible?

Tried something like: Swipe::all()->sortBy('user_id')->unique('user_id')

But latest record inside the group is not correct

CodePudding user response:

You can try using the groupBy and max methods to achieve your desired result:

$latestSwipes = Swipe::all()->groupBy('user_id')->map(function($swipes) {
return $swipes->max('created_at');
});

This will group all the swipes by user_id and then return only the swipe with the latest created_at timestamp for each group. This will return a collection of the latest swipes by user_id with no duplicates.

Alternatively, you can use the sortByDesc and unique methods to achieve a similar result:

$latestSwipes = Swipe::all()->sortByDesc('created_at')->unique('user_id');

This will first sort the swipes in descending order by created_at timestamp and then remove any duplicate user_id values, leaving only the latest swipe per user_id in the collection.

  • Related