da.eXecutoR
da.eXecutoR

Reputation: 313

Laravel Eloquent filter on children

I've got the following relationship:

Customers -> hasMany (Contracts)

Now I want to get all customers including all contracts that have a given condition:

$c = Customer::with('contracts','contracts.service','contracts.contractpos')
    ->whereHas('contracts', function ($query) {
        $query
        ->where('invoice_next','=',$this->invoice_next)
        ->groupBy('customer_id');
    })
    ->orderBy('company')
    ->get();

However, I get all customers that have a contract fullfilling the condition (invoice_next = $this->invoice.next ), but also all the contracts that doesn't match the condition.

So filtering the customers works, but I then get all of the customers contracts instead of only the ones that are due. Where do I make the mistake?

It seems like the "where" condition in the subquery only works for the customers but doesn't filter the children (contracts).

Thanks for any hint in the right direction.

Greetings eXe

Upvotes: 1

Views: 3095

Answers (1)

yrv16
yrv16

Reputation: 2275

Try this:

$c = Customer::with(['contracts' => function($query){
          $query->where('invoice_next','=',$this->invoice_next)
          ->with(['service', 'contractpos'])
          ->groupBy('customer_id');
     }])
    ->whereHas('contracts', function ($query) {
        $query->where('invoice_next','=',$this->invoice_next);            
    })
    ->orderBy('company')
    ->get();

Upvotes: 5

Related Questions