Laravel 更新多个 hasMany / belongsToMany 关系
Laravel updating multiple hasMany / belongsToMany relationships
我继承了一个有几个 CRUD 表单的项目...在创建表单上,我们需要为 hasMany
和 belongsToMany
关系创建条目。所以基本上我得到的是以下
$movie = Movie::create($request->validated());
// Then to save the belongsToMany
foreach ($request['actors'] as $actor) {
// do some data manipulation
$actor = Actor::where('code', $actor->code)->first();
$movie->actors()->attach($actor);
}
// Save the hasMany
foreach ($request['comments'] as $comment) {
// do some data manipulation
$movie->comments()->create([
'title' => $comment['title'],
'body' => $comment['body'],
]);
}
我不确定这是否是最好的方法,但它似乎有效。
我遇到的问题是,在 edit
表格中,可以编辑、添加或删除这些演员/评论,我不确定如何更新它们。是否可以更新它们,还是删除现有的关系数据并重新添加它们会更好?
我从来没有更新过关系,只是添加了它们,所以我什至不确定如何开始。
如有任何帮助,我们将不胜感激。
与laravel doc suggested一样,您可以使用saveMany()
方法来存储关系实例。
// Save the hasMany
foreach ($request['comments'] as $comment) {
$comments[] = [
new Comment([
'title' => $comment['title'],
'body' => $comment['body'],
]);
];
}
!empty($comments) && $movie->comments()->saveMany($comments);
对于删除和更新,您应该定义两个路由,一个用于更新评论,一个用于删除评论。
Route::patch('movie/{movie}/comment/{comment}',[MovieController::class,'updateComment']);
Route::delete('movie/{movie}/comment/{comment}',[MovieController::class,'deleteComment']);
我继承了一个有几个 CRUD 表单的项目...在创建表单上,我们需要为 hasMany
和 belongsToMany
关系创建条目。所以基本上我得到的是以下
$movie = Movie::create($request->validated());
// Then to save the belongsToMany
foreach ($request['actors'] as $actor) {
// do some data manipulation
$actor = Actor::where('code', $actor->code)->first();
$movie->actors()->attach($actor);
}
// Save the hasMany
foreach ($request['comments'] as $comment) {
// do some data manipulation
$movie->comments()->create([
'title' => $comment['title'],
'body' => $comment['body'],
]);
}
我不确定这是否是最好的方法,但它似乎有效。
我遇到的问题是,在 edit
表格中,可以编辑、添加或删除这些演员/评论,我不确定如何更新它们。是否可以更新它们,还是删除现有的关系数据并重新添加它们会更好?
我从来没有更新过关系,只是添加了它们,所以我什至不确定如何开始。
如有任何帮助,我们将不胜感激。
与laravel doc suggested一样,您可以使用saveMany()
方法来存储关系实例。
// Save the hasMany
foreach ($request['comments'] as $comment) {
$comments[] = [
new Comment([
'title' => $comment['title'],
'body' => $comment['body'],
]);
];
}
!empty($comments) && $movie->comments()->saveMany($comments);
对于删除和更新,您应该定义两个路由,一个用于更新评论,一个用于删除评论。
Route::patch('movie/{movie}/comment/{comment}',[MovieController::class,'updateComment']);
Route::delete('movie/{movie}/comment/{comment}',[MovieController::class,'deleteComment']);