Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a Builder whose every relation's model matches a specific condition

I have a Order model and a Transaction model. A order can have one or multiple transactions.

I want those orders whose every transactions status are 'Pending'.

I tried to implement like below:

$builder = Order::with('transactions')->latest('id');

if(condition)
{
    $builder->whereHas('transactions', function ($query) {
        $query->where('status', 'Pending');
    });
}

This returns those order whose at least one transaction has 'Pending' status. But I want those orders whose every transactions have status 'Pending'.

like image 924
Najmus Sakib Avatar asked Nov 22 '25 20:11

Najmus Sakib


1 Answers

I think you can do it easily using the opposite way, like:

$builder = Order::with('transactions')->latest('id');

if($condition)
{
    $builder = $builder->has('transactions')
        ->whereDoesntHave('transactions', function ($query) {
            $query->where('status','!=', 'Pending');
        });
}

$result = $builder->get();

the 'has' method insure that there is transactions, and whereDoesntHave insure that all transactions are in pending state

like image 145
OMR Avatar answered Nov 24 '25 09:11

OMR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!