In Laravel, is it possible to summarize the attribute of related models using the withCount method?

I have 3 models similar to: Prize โ†’ TimeSlot โ†’ Winner, with their respective relationship methods $ prize-> hasMany (TimeSlot) and $ prize-> hasManyThrough (Winner, TimeSlot).

I am trying to count the number of winners and the number of time slots in one eloquent request.

Here is the request:

$prizes = $prizes->withCount(['winners', 'timeSlots' => function ($query) {
    $query->sum('min'); // min is an attribute on TimeSlot
}])->get();

      

This gives me the number of winners with the 'winners_count' attribute for each prize. I thought this would give me the "count of numbers" of time slots for each prize, but the request breaks down into that part with an error like:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'prizes.id' in 'where clause' 
(SQL: select sum(`min`) as aggregate from `time_slots` where `time_slots`.`prize_id` = `prizes`.`id`)

      

The withCount method documentation shows how to constrain a query (e.g. with a where clause), but not with an amount like that.

PS: I already know how to do this, for example:

$prizes = $prizes->with('timeSlots')->withCount('winners')->get();

$numOfWinners = $prizes->sum('winners_count');

$numOfAvailablePrizes = $prizes->sum(function ($prize) {
    return $prize->timeSlots()->sum('min');
});

      

But I thought the single query version would save me a few useless loops ...

Thanks for answers!

+3


source to share


1 answer


try it

$query->withCount(['timeSlots AS timeslots_sum' => function ($query) {
    $query->select(DB::raw('SUM(min) as timeslots_sum'));
}]);

      



He will return

"timeslots_sum" => "123" // total

      

0


source







All Articles