简体   繁体   English

Laravel 更新多个 hasMany / belongsToMany 关系

[英]Laravel updating multiple hasMany / belongsToMany relationships

I have inherited a project that has aa few CRUD forms... On the create form we need to create entries for a hasMany and belongsToMany relationship.我继承了一个项目,它有几个 CRUD forms... 在创建表单上,我们需要为hasManybelongsToMany关系创建条目。 So basically what i have got is the following所以基本上我得到的是以下

$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'],
  ]);
}

I'm not sure if this is the best way of doing this, but it seems to work.我不确定这是否是最好的方法,但它似乎有效。

The problem I am having is that in the edit form, these actors / comments can be edited, added to or deleted and i am unsure of how to go about updating them.我遇到的问题是,在edit表单中,可以编辑、添加或删除这些演员/评论,我不确定如何更新它们。 Is it possible to update them, or would it be better to delete the existing relationship data and re-add them?是否可以更新它们,还是删除现有的关系数据并重新添加它们会更好?

I have never updated relationships, only added them so i am unsure how to even start.我从来没有更新过关系,只是添加了它们,所以我不确定如何开始。

Any help would be greatly appreciated.任何帮助将不胜感激。

As laravel doc suggested you can use saveMany() method for storing relationship instances.正如laravel 文档建议的那样,您可以使用saveMany()方法来存储关系实例。

// Save the hasMany 
foreach ($request['comments'] as $comment) {
  
  $comments[] = [
    new Comment([
      'title' => $comment['title'],
      'body' => $comment['body'],
    ]);  
  ];
}

!empty($comments) && $movie->comments()->saveMany($comments);

For deletion and update you should define two routes, one for updating comment and one for deleting comment.对于删除和更新,您应该定义两条路由,一条用于更新评论,一条用于删除评论。

Route::patch('movie/{movie}/comment/{comment}',[MovieController::class,'updateComment']);
Route::delete('movie/{movie}/comment/{comment}',[MovieController::class,'deleteComment']);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM