【问题标题】:Laravel updating multiple hasMany / belongsToMany relationshipsLaravel 更新多个 hasMany / belongsToMany 关系
【发布时间】:2022-01-16 05:27:31
【问题描述】:

我继承了一个有几个 CRUD 表单的项目......在创建表单上,我们需要为 hasManybelongsToMany 关系创建条目。所以基本上我得到的是以下内容

$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 表单中,可以编辑、添加或删除这些演员/cmets,我不确定如何更新它们。是否可以更新它们,还是删除现有的关系数据并重新添加它们会更好?

我从未更新过关系,只是添加了它们,所以我什至不确定如何开始。

任何帮助将不胜感激。

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    作为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']);
    

    【讨论】:

    • 嘿,谢谢...我的资源控制器中有更新路线,但我不确定how 是否更新关系
    • 类似$movie->comments()->where('id', $comment->id)->update(['title'=>'new title']); ?
    • 我在 saveMany 中遇到错误,传递给 Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() 的参数 1 必须是 Illuminate\Database\Eloquent\Model 的实例,给定数组
    • @CodeSauce 如果您只保存一条评论,您应该使用save(),如果您选择在一行中保存许多cmets,您应该使用saveMany()。您不能将一组 cmets 传递给 save() 方法,因为它需要一个 Model 类的实例(在本例中为 Comment)。
    猜你喜欢
    • 2018-01-03
    • 2021-03-22
    • 2021-10-07
    • 2014-12-30
    • 1970-01-01
    • 1970-01-01
    • 2019-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多