我繼承了一個有幾個 CRUD 表單的專案......在創建表單上,我們需要為 ahasMany和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表單中,可以編輯、添加或洗掉這些演員/評論,我不確定如何更新它們。是否可以更新它們,或者洗掉現有的關系資料并重新添加它們會更好嗎?
我從未更新過關系,只是添加了它們,所以我什至不確定如何開始。
任何幫助將不勝感激。
uj5u.com熱心網友回復:
正如laravel doc建議您可以使用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']);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/379619.html
