Skip to content

how i can use withSum that should be eager loaded on every query like withCount #44515

Answered by kverstae
samehdoush asked this question in General
Discussion options

You must be logged in to vote

A possible solution would be to add a global query scope (https://laravel.com/docs/9.x/eloquent#global-scopes) to your user model (or whatever model you want).
This would look something like this:

// CountAndSumScope

class CountAndSumScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        $builder->withCount([...])->withSum([...]);
    }
}

// User

protected static function booted()
{
    static::addGlobalScope(new CountAndSumScope);
}

This code is untested, but I think this idea could work

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by samehdoush
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants