0

in laravel 9 I implement many to many relationship.

I have three table, shop , product and product_shop table.

each shop can have number of every single product. and each product can exist in multiple shops.

the question is how can I insert/get the number of product inside the product_shop table?

what relationship syntax I have to use?

product_shop table :

$table->unsignedInteger('product_id');
$table->unsignedInteger('shop_id');
$table->unsignedInteger('number');

$table->foreign('product_id')->references('id')->on('products');
$table->foreign('shop_id')->references('id')->on('shops');

thanks

0

1 Answer 1

1

You can use pivot. For example,

$product = $shop->products()->withPivot(['number'])->first();
$number = $product->pivot->number;

And if you want to insert,

$shop->products()->attach([$product_id => ['number' => $your_value]]);
3
  • $product = $shop->products()->withPivot(['number'])->first(); how can I set the query? for example , where('number', '>' , "5') ? Jun 16, 2022 at 5:59
  • 1
    $product = $shop->products()->withPivot(['number'])->wherePivot('number', '>', 5)->get(); It works for me
    – devcrazy
    Jun 16, 2022 at 6:01
  • sorry, I could not found that how can I update the number field id pivot table ? Jun 18, 2022 at 10:30

Not the answer you're looking for? Browse other questions tagged or ask your own question.