Home > Software design >  Laravel relationship with multiple table with pivot
Laravel relationship with multiple table with pivot

Time:11-25

I have 3 tables and pivot (product has options)

-products
 -> id
 -> name
 -> price

-options
 -> id
 -> name
 -> option_group_id 

-option_groups
 -> id
 -> name

-option_products
 -> option_id
 -> product_id

I get product options with

public function options()
{
    return $this->belongsToMany(\App\Models\Option::class, 'option_products');
}

but I want to get the option groups from a product model

CodePudding user response:

You can directly access the option_groups property from an option. Thus, you don't need another relation. If you want to have all option groups, you can eager load them on the relation using another method on the model. If you only need the option groups, you may then map the resulting collection into a collection of the option groups.

Example:

public function optionsWithGroups()
{
    return $this->options()
        ->with('group')
        ->get();
}

// ...or...

public function optionGroups()
{
    return $this->options()
        ->with('group')
        ->get()
        ->map(fn($option) => $option->group);
}

CodePudding user response:

This can be achieved with "nested eager loading".

Products::with('options','options.groups'...)->get();

https://laravel.com/docs/8.x/eloquent-relationships#nested-eager-loading

CodePudding user response:

I think what you want is a hasManyThrough relationship. Something like:

public function optionGroups()
{
  return $this->hasManyThrough(OptionGroup::class, Option::class);
}

You may need to explicitly set some of the keys (see key conventions).

  • Related