praveen.menezes
praveen.menezes

Reputation: 55

Laravel Defining Complex Relationships

I need help in defining relationships for the following tables

product
  id
  name

modifier
  id
  name

modifier_items
  id
  modifier_id
  name
  price

modifier_product
  id
  modifier_id
  product_id

One Product may have multiple Modifiers

Please help me define a relationship in Laravel that outputs the expected results

Expected Result in Product Model

i.e 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
    },
  ]

Upvotes: 1

Views: 74

Answers (1)

bhavinjr
bhavinjr

Reputation: 1763

Try this

Model Product.php

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

Model Modifier.php

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

You can retrive

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

Upvotes: 1

Related Questions