vincent15000's avatar

How to use withSum() with a condition where() ?

Hello,

Here is a query.

$teachingUnitSubjects = TeachingUnitSubject::
    with(['subject' => function($query) {
        return $query->select('id', 'name');
    }])
    ->withSum('courses', 'hours_number')
    ->where('teaching_unit_id', $teachingUnitId)->get();

I'd like to add a where() closure on the withSum. How may I do it ?

Thanks for your help.

Vincent

0 likes
10 replies
vincent15000's avatar

Hello @kevinbui I have tried, I have replaced with an array with a closure, but it doesn't work.

Do you have an example ?

vincent15000's avatar

Hmmm ... have you tried this ? Does it work ?

I just tested and it doesn't work.

SilenceBringer's avatar

@vincent15000 I didn't try exactly this code, but similar

How it doesn't work? Didn't filter the results? Or it throws error?

If you will provide more details about which relationship sum you want to filter and how, we will try to help you

vincent15000's avatar

It throws an error ...

Too few arguments to function Illuminate\Database\Eloquent\Builder::withSum()

It says that I pass only one argument (an array) and 2 arguments are required. So the method doesn't allow an array.

I'd like to do is something like this.

->withSum([
    'courses' => fn ($query) => $query->where('canceled', false),
    'hours_number'
])

To retrieve the sum of hours_number only for the courses with canceled equals false.

I just found the solution, thanks to you ;).

->withSum(
    ['courses' => function($query) {
        $query->where('canceled', false);
    }],
    'hours_number'
)

The array must be only for the first argument.

9 likes
iamspydey's avatar

@SilenceBringer it is throwing error too few arguments passed in withSum() method

Fix it by this syntext

->withSum(
    [ 'courses' => fn ($query) => $query->where('column', 'value')],
    'hours_number'
)
6 likes
vincent15000's avatar

@Azade-ghasemi You can create a new post and detail your problem, so we can help you ;).

Please or to participate in this conversation.