I would like to find out how many Users
have Swipes
per day without duplicates of user_id
within group.
So if a User
has swiped multiple times on a day, I want the User
only show once per group (per day). I am not really interested in the actual Swipes
but rather in the swipe count
per day.
I tried:
Swipe::all()->groupBy(function($item){ return $item->created_at->format('d-M-y'); })->unique('user_id')
CodePudding user response:
To remove duplicates from the groupBy
, you can use the distinct()
method in combination with the groupBy()
method. This will group the Swipes by day, and then only include distinct user_id
values in each group:
Swipe::all()->groupBy(function($item){ return $item->created_at->format('d-M-y'); })->distinct('user_id')
Alternatively, you can use the distinct()
method with a callback function to specify which columns to consider when determining uniqueness:
Swipe::all()->distinct(function ($item) {
return $item->created_at->format('d-M-y') . '-' . $item->user_id;
})
This will group the Swipes by day and user_id
, and only include distinct combinations of these values in the result. You can then use the count()
method to get the number of unique Swipes per day.
Swipe::all()->distinct(function ($item) {
return $item->created_at->format('d-M-y') . '-' . $item->user_id;
})->count();
CodePudding user response:
To remove duplicate data, you can use unique()
.
I create an example for you. I have dummy data like
So you want the result is data grouped by created_at and on every date return how many users swipe it but without duplicate user?
The code should be like:
$collect = Swipe::all()->groupBy(function($data){
return $item->created_at->format('d-M-y');
})->transform(function($dataGrouped,$date){
return [
$date => $dataGrouped->unique('user_id')
];
});
The result will be like: