LoginSignup
39
22

More than 5 years have passed since last update.

[Laravel5.7] Eloquent リレーションにおける saveメソド と createメソド の特徴

Posted at

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 メソド

savesaveMany と似た様な動きをする。
ただし、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.',
    ],
]);

公式ドキュメント

39
22
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
39
22