Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query relation in laravel scope

I have the following scope that I would like to amend slightly:

function scopeNotRunOut($query)
{
    return $query->has('redemptions', '<', DB::raw('quantity'));
}

This return all models where the related redemptions count is less than the quantity column. The redemptions table has a column for user_id so how would I tweak this so that it only counts redemptions where the user_id column is a given value?

like image 534
geoffs3310 Avatar asked Feb 03 '26 19:02

geoffs3310


1 Answers

Managed to work it out myself in the end, here is the answer:

function scopeCustomerMaxUsesValid($query, $user_id)
{
    return $query->whereHas('redemptions', function($query) use ($user_id) {
        $query->where('user_id', '=', $user_id);
    }, '<', DB::raw('quantity'));
}
like image 165
geoffs3310 Avatar answered Feb 06 '26 08:02

geoffs3310