【问题标题】:How to clear relationship property for Laravel Eloquent Model?如何清除 Laravel Eloquent 模型的关系属性?
【发布时间】:2018-01-16 01:29:53
【问题描述】:

有两种型号

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 事件已触发,但旧图像并未从$item 中删除。它们实际上已从数据库中删除,但 $item 没有更新(就像在 $item->images()->delete() 的情况下一样)并且仍然保留引用。

有没有办法清除关系?在伪代码中:

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

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    您可以通过以下方式重新加载图像数据:

    $item->load('images');
    

    【讨论】:

    • 在删除旧的和创建新的之间添加$item->images = []; 不起作用。但是在创建后立即添加 $item->load('image') 可以确保 $item 是最新的。
    • @KārlisJanisels 感谢您的反馈,我已经更新了答案。