如何在 Laravel 5 中更新一对多 (hasMany) 关系

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45775736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:31:23  来源:igfitidea点击:

How to UPDATE one to many (hasMany) relation in Laravel 5

phplaravellaravel-5ormeloquent

提问by sanjay ojha

Well, I am using Laravel 5.4 and reached in a situation where I need to update one to many (hasMany) relation ship. I have a productstable and a product_imagestable. Below is my relation definition in each model.

好吧,我正在使用 Laravel 5.4,并且遇到了需要更新一对多 (hasMany) 关系的情况。我有一张products桌子和一张product_images桌子。以下是我在每个模型中的关系定义。

//Product.php
public function productImages()
{
    return $this->hasMany('App\ProductImage');
}

//ProductImage.php
public function product()
{
    return $this->belongsTo('App\Product');
}

I am giving a form interface to update existing product. In that I have 4 optional file upload input html tag for updating or adding (new) images for the product. Remember all these 4 image upload is optional.

我正在提供一个表单界面来更新现有产品。因为我有 4 个可选的文件上传输入 html 标签,用于更新或添加产品的(新)图像。请记住所有这 4 个图像上传都是可选的。

So my question is what is the best approach(laravel way) to

所以我的问题是什么是最好的方法(laravel 方法)

  1. update existing entries in product_imagestable
  2. add new one if provided
  3. delete existing if it is removed
  1. 更新现有条目product_images
  2. 如果提供,请添加新的
  3. 如果删除,则删除现有

I know the attachor detachmethod (sync) to remove all and then add the provided one. But I want to maintain the id if we are replacing any existing image.

我知道attachordetach方法 ( sync) 删除所有,然后添加提供的一个。但是如果我们要替换任何现有图像,我想保留 id。

回答by Chad Kieffer

Old question, but here's an answer.

老问题,但这里有一个答案。

1 and 2- Laravel's updateOrCreate() method will update existing records and insert new records if an existing image ID is not provided. See "updateOrCreate" under Eloquent ORM's Update documentation.

1 和 2- 如果未提供现有图像 ID,Laravel 的 updateOrCreate() 方法将更新现有记录并插入新记录。请参阅 Eloquent ORM 的更新文档下的“updateOrCreate” 。

$images = App\ProductImage::updateOrCreate(
    ['id' => $id],
    ['field1' => $field1, 'field2' => $field2]
);

3- To delete, add a delete checkbox to your form which passes target image IDs as an array...

3- 要删除,请在表单中添加一个删除复选框,该复选框将目标图像 ID 作为数组传递...

<input type="checkbox" name="imgsToDelete[]" value="{{$product->image->id}}">
<label>Delete</label>

...then, in your product update method, simply pass the field array to Eloquent's destroy() method.

...然后,在您的产品更新方法中,只需将字段数组传递给 Eloquent 的 destroy() 方法。

$imgsToDelete = $request->get('imgsToDelete');
ProductImage::destroy($imgsToDelete);

Don't forget to delete stored images from the file system!

不要忘记从文件系统中删除存储的图像!