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'.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With