Ad

OctoberCMS Eager Loading With And Where Condition

- 1 answer

I would like to filter my query with where condition. Let's say I have a Product model, this has a relationship with the Buyer model. I want to get the list of Product model bought from a group of Buyers where the Buyer is 65yo and above.

$query = Product::with('Buyer')
  ->where('Buyer.age','>=',65)
  ->get();

However, I couldn't place the where condition like this, it shows "Unknown column for Buyer.age". Please advise how can I filter my result?

Ad

Answer

Give this a try.

$query = Product::with('Buyer')
   ->whereHas('Buyer', function($q){  // whereHas will only return products whose buyer is >= 65
       $q->where('age','>=',65);
   })
  ->get();
Ad
source: stackoverflow.com
Ad