LoginSignup
0
0

More than 3 years have passed since last update.

[自分メモ]複数レコードを配列にして一括でattach()

Posted at

目的

中間テーブルを利用して複数レコードを一気に登録する場合、attach($配列)のような形で登録することができます。
attach()の引数はprimary keyなので、$primaryKeyの配列を作らなければなりません。

やり方

controller.php
$tagIds = array(); 
foreach ($request->tag as $val) {
  $tagIds[] = Tag::select('tag_id')->where('tag_name', $val)
              ->first()->tag_id;
}
$post->tags()->attach($tagIds);
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0