[英]How to clear relationship property for Laravel Eloquent Model?
有两种型号
item
image
它们之间有hasMany
关系(项目有很多图像)
我需要删除项目的所有图像,然后创建新图像,并将该项目与新图像一起传递以进行查看。
$item->images()->delete();
foreach ($this->new_images as $public_id){
$item->images()->create([
'public_id' => $public_id
]);
}
但是,在这种情况下,我错过了deleted
删除图像上的Eloquent事件,这在这种情况下很重要。 我试图分别删除它们:
$item->images->each(function($image){
$image->delete();
});
foreach ($this->new_images as $public_id){
$item->images()->create([
'public_id' => $public_id
]);
}
现在deleted
触发deleted
事件,但是不会从$item
删除旧图像。 它们实际上已从数据库中删除,但是$item
不会更新(就像$item->images()->delete()
),并且仍然保留引用。
有没有清除关系的方法? 用伪代码:
//delete images one-by-one
$item->images = null;
// now add the new images
您可以使用以下方法重新加载图像数据:
$item->load('images');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.