Laravel 多対多リレーション
- 複数のuserが複数のproductをもてる→多対多
- 中間pivotテーブルとしてcartを作成し、それぞれ1対多の関係にする
cartsテーブル作成
root@f6999f3b8a5b:/var/www/html# php artisan make:model Cart -m
外部キー設定を記述
<?php public function up() { Schema::create('carts', function (Blueprint $table) { $table->id(); //ownerを削除したらshopも消える、shopが消えたらproductも消えるようにする→cascade $table->foreignId('user_id')->constrained()->onUpdate('cascade')->onDelete('cascade'); $table->foreignId('product_id')->constrained()->onUpdate('cascade')->onDelete('cascade'); $table->integer('quantity'); $table->timestamps(); }); }
カートにいれるときにuser_id
,product_id
, quantity
をまとめていれる設定
<?php class Cart extends Model { use HasFactory; protected $fillable = [ 'user_id', 'product_id', 'quantity' ];
リレーション設定
多対多の関係は、belongsToManyメソッドの結果を返すメソッドを作成して定義
中間テーブルのカラムを取得するとき、(今回の場合、userとproductが多対多)
pivot
属性をつけることで、中間テーブルの値を取得できる。また、中間テーブルに追加の属性を取得したいとき、(今回はcartsテーブルのidとquantity)
モデル側でwithPivot
の引数に必要な値を追記する。
<?php use App\Models\User; public function users() { return $this->belongsToMany(User::class,'carts') ->withPivot(['id', 'quantity']); }
<?php use App\Models\Product; public function products() { return $this->belongsToMany(Product::class, 'carts') ->withPivot(['id', 'quantity']); }