Eloquentでは新しく作ったモデルとのリレーションに使える save メソド、 create メソドなどが用意されている。
※ 5.7 から追加された push についてはこちら。
save メソド
リレーションの save メソドを使えば、親テーブルのidを子テーブル該当のカラムに直接入れることが可能。
$comment = new App\Comment(['message' => 'A new comment.']);
$post = App\Post::find(1);
//これで Comment の post_id に Post の id が入る
$post->comments()->save($comment);
動的プロパティ -> で呼ぶのではなく、メソド comments() でよんでリレーションインスタンスをとってきているのがミソ。
saveMany メソド
複数のモデルについて同様にセーブかつ親のidを入れたいときは saveMany メソドが使える。
$post = App\Post::find(1);
$post->comments()->saveMany([
new App\Comment(['message' => 'A new comment.']),
new App\Comment(['message' => 'Another comment.']),
]);
create メソド
save や saveMany と似た様な動きをする。
ただし、save はEloquentまるごとのインスタンスを受け入れるのに対し、 create が受け入れるのはPHPの配列 という点で異なる。
$post = App\Post::find(1);
$comment = $post->comments()->create([
'message' => 'A new comment.',
]);
こちらにも複数のリレーションモデルがいっぺんに作れる createMany が用意されている。
$post = App\Post::find(1);
$post->comments()->createMany([
[
'message' => 'A new comment.',
],
[
'message' => 'Another new comment.',
],
]);
公式ドキュメント