Laravel定义复杂的关系

时间:2019-03-21 08:49:59

标签: php mysql laravel relationship

我需要帮助定义下表的关系

product
  id
  name

modifier
  id
  name

modifier_items
  id
  modifier_id
  name
  price

modifier_product
  id
  modifier_id
  product_id

一个产品可能具有多个修饰符

请帮助我定义  Laravel中的一个关系可以输出预期的结果

产品模型中的预期结果

  

即Product :: with([...])-> get()

  id: 1,
  name: "Product name", // (Product name)
  modifiers: [
    {
      id: 1, // modifier_id
      name: "some name 1",
      items: [
        {
          id: 1, // modifier_item_id,
          name: "modifier name",
          price: 10
        },
        {
          id: 2, // modifier_item_id,
          name: "modifier name",
          price: 20
        }
      ]
    },
    {
      name: "some name 2",
      items: [] // Collection of Modifier items
    },
  ]

1 个答案:

答案 0 :(得分:1)

尝试一下

模型Product.php

public function modifiers()
{
   return $this->belongsToMany(Modifier::class, 'modifier_product'); // Modifier::class is Modifier Model and modifier_product is table name
}

模型Modifier.php

public function modifierItems()
{
    return $this->hasMany(ModifierItem::class); //modifier_items Model
}

您可以检索

Product::with('modifiers')->get(); //get product with modifiers
or
Product::with('modifiers.modifierItems')->get(); //get product with modifiers and modifier_items