Laravel 8 保存方法
Eloquent 为新模型添加关联提供了便捷的方法。例如,也许你需要添加一个新的 Comment 到一个 Post 模型中。你不用在 Comment 中手动设置 post_id 属性,就可以直接使用关联模型的 save 方法将 Comment 直接插入:
$comment = new App\Models\Comment(['message' => 'A new comment.']);
$post = App\Models\Post::find(1);
$post->comments()->save($comment); 需要注意的是,我们并没有使用动态属性的方式访问 comments 关联。相反,我们调用 comments 方法来获得关联实例。save 方法将自动添加适当的 post_id 值到 Comment 模型中。
如果你需要保存多个关联模型,你可以使用 saveMany 方法:
$post = App\Models\Post::find(1);
$post->comments()->saveMany([
new App\Models\Comment(['message' => 'A new comment.']),
new App\Models\Comment(['message' => 'Another comment.']),
]); save 和 saveMany 方法不会将新模型加载到父模型上。 如果你想在使用 save 或 saveMany 方法之后访问该关联,需要使用 refresh 方法来重新加载模型及其关联:
$post->comments()->save($comment);
$post->refresh();
// 所有评论,包括新保存的评论...
$post->comments;