简体   繁体   English

Laravel 与多个表的关系与 pivot

[英]Laravel relationship with multiple table with pivot

I have 3 tables and pivot (product has options)我有 3 张桌子和 pivot(产品有选项)

-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但我想从产品 model 中获取选项组

You can directly access the option_groups property from an option.您可以直接从选项访问option_groups属性。 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.如果您想拥有所有选项组,您可以使用 model 上的另一种方法将它们预先加载到关系上。 If you only need the option groups, you may then map the resulting collection into a collection of the option groups.如果只需要选项组,则可以将 map 生成的集合放入选项组的集合中。

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);
}

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 https://laravel.com/docs/8.x/eloquent-relationships#nested-eager-loading

I think what you want is a hasManyThrough relationship .我认为您想要的是hasManyThrough关系 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 ).您可能需要显式设置一些键(请参阅键约定)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM