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

aref razavi
  • 413
  • 2
  • 12

1 Answers1

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]]);
devcrazy
  • 505
  • 5
  • 14
  • `$product = $shop->products()->withPivot(['number'])->first();` how can I set the query? for example , `where('number', '>' , "5')` ? – aref razavi Jun 16 '22 at 05:59
  • 1
    `$product = $shop->products()->withPivot(['number'])->wherePivot('number', '>', 5)->get();` It works for me – devcrazy Jun 16 '22 at 06:01
  • sorry, I could not found that how can I update the `number` field id pivot table ? – aref razavi Jun 18 '22 at 10:30