Skip to content
Advertisement

Laravel hasMany with condition based on additional relationship

In my issue, I have a shop. A shop has many aisles and each aisle has many items. I have created 3 tables:

Shop -> id and name

Aisles -> id, shop_id, name

Aisle_items -> id, aisle_id, name

I’m trying to retrieve the shop and a list of aisles that have items in a single query.

My shop model has a hasMany function of aisles():

public function aisles() {
   return $this->hasMany(Aisle::class, 'shop_id', 'id')->orderBy('name', 'ASC');
}

and my Aisle model has a hasMany function of items():

public function items() {
  return $this->hasMany(AisleItem::class)->orderBy('name');
}

What do I need to add to the aisles() function to retrieve only aisles with items?

Would it be better in the query itself to find this information as opposed to through the model?

Advertisement

Answer

You can use has to only retrieve records that actually have a relationship

$aisles = $shop->aisles()->has('items')->get()
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement