简体   繁体   English

如何清除Laravel雄辩模型的关系属性?

[英]How to clear relationship property for Laravel Eloquent Model?

There are two models 有两种型号

item
image

and there is hasMany relationship between them (item has many images) 它们之间有hasMany关系(项目有很多图像)

I need to delete all images of item, then create new images and pass the item with new images to view. 我需要删除项目的所有图像,然后创建新图像,并将该项目与新图像一起传递以进行查看。

$item->images()->delete();
foreach ($this->new_images as $public_id){
    $item->images()->create([
         'public_id' => $public_id
    ]);
}

However in this case I missed the deleted Eloquent event on deleted images which is important in this case. 但是,在这种情况下,我错过了deleted删除图像上的Eloquent事件,这在这种情况下很重要。 I tried to delete them seperately: 我试图分别删除它们:

$item->images->each(function($image){
    $image->delete();
});
foreach ($this->new_images as $public_id){
    $item->images()->create([
         'public_id' => $public_id
    ]);
}

And now the deleted event in fired however the old images are not removed from $item . 现在deleted触发deleted事件,但是不会从$item删除旧图像。 They are actually deleted from DB but the $item is not updated (as it was in case of $item->images()->delete() ) and still holds references. 它们实际上已从数据库中删除,但是$item不会更新(就像$item->images()->delete() ),并且仍然保留引用。

Is there a way to clear the relation? 有没有清除关系的方法? In pseudo-code: 用伪代码:

//delete images one-by-one
$item->images = null;
// now add the new images

您可以使用以下方法重新加载图像数据:

$item->load('images');

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

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