2
votes

In Laravel, is it possible to put a relationship within a relationship?

Basically, I already have a relationship set up, but I then need another relationship for that relationship (if that makes sense).

My two models:

  • Store
  • Supplier

My relationship model for Store and Supplier:

  • SupplierStore
  • store_id
  • supplier_id

As you can see, I have many stores and suppliers, each of whom can relate to each other through the SupplierStore table.

This works perfectly.

My problem is that for each relationship (of Store and Supplier) there can be many Delivery Days.

My HasMany relationship:

DeliveryDay
supplier_store_id
day

I thought if I go into the SupplierStore model and add:

public function days()
{
 return $this->hasMany('App\DeliveryDay');
}

Would work, but there is no way I can seem to access this data through eloquent?

I was hoping to do something like this:

$supplier = Supplier::find($id); $supplier->store->pivot->days

The pivot (SupplierStore) would hold the relationship of that specific relation and I could grab the days.

Can anyone help me figure out what I need to do to achieve this? Your time is much appreciated. After googling for hours, my head hurts so much. :)

1
is SupplierStore already a model?dparoli
Yeah, SupplierStore is a model. It's the model which is used for the BelongsToMany relationship between Supplier and Store. That model itself also has a relationship of HasMany for DeliveryDays.Mr Digital
I'm having the same problem. I need to define a relationship inside the pivot model for making easier queries. How did you solve it?Zalo

1 Answers

0
votes

You could access each day like this:

public function getDays($id)
{
 $supplier = Supllier::find($id);

 foreach($supplier->stores() as $store)
 {
   foreach($store->days() as $day)
   {
    echo $day->day;
   }
 }
}

Or get all days

$supplier->stores->days;