There are two models
item
image
and there is hasMany
relationship between them (item has many images)
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. 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
. 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.
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');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.