【Laravel】belongsToMany(多対多)の中間テーブル(Pivot)にリレーションのid以外の値を保存する

Laravelで2つのテーブルがbelongsToManyの多対多でリレーションしている場合に、中間テーブルにリレーション用のidをもつカラムが最低でも2つありますよね。post_idとtag_idみたいな。

今回はその中間テーブルにid以外の値を保存する方法を説明します。

belongsToMany(多対多)の中間テーブル(Pivot)にリレーションのid以外の値を保存する

// post model

public function tags()
{
  return $this->belongsToMany(Tag::class)
}

// tag model

public function posts()
{
  return $this->belongsToMany(Post::class)
}

その場合、一般的にはこのように紐付けをすると思います。

$post->tags()->attach($tag->id);

でももし、その他にcolorというカラムも持っている場合にcolorのカラムに値を保存するときどうしたいいでしょう?

答えから。attach またはsyncWithPivotValues で第三引数にfalseを渡すとできる。

$params = ['color' =>  'red' ]; // key => value
$post->tags()->syncWithPivotValues($tag, $params, false);

まあ一般的にはattach()で中間テーブルにレコード生成すると思いますので、こうなります。

$params = ['color' =>  'red' ]; // key => value
$post->tags()->attach($tag->id, $params);

ちなみに第一引数の$tag->idはモデルのまま渡しても大丈夫そう。

ちなみにupdateをしたいときは`updateExistingPivot` を使いましょう。

 

今回解説したメソッドはLaravelの公式サイトだとこちら。

https://laravel.com/api/9.x/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.html#method_attach

https://laravel.com/api/9.x/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.html#method_syncWithPivotValues