Laravel 5:如何检索已删除的相关模型?

时间:2022-10-15 23:16:34

I have the following models; Brand, Image, and Image_size. Brand has one image and image has many image_sizes. All of these models use soft deletes and the deleting aspect is fine. However if I then wanted to restore a brand that has been deleted I also need to restore the related image and image_size models.

我有以下模型;品牌形象,Image_size。品牌有一个形象,形象有许多形象大小。所有这些模型都使用软删除,删除方面也没问题。但是,如果我想要恢复被删除的品牌,我还需要恢复相关的图像和image_size模型。

I have been looking into using model events so that when my Brand model is being restored I can get the image and restore that, and then I'll have a similar event in the image model to get the the image sizes and restore those. I'm struggling to get the deleted image record though for the brand. This is what I have I am trying to do in my brand model:

我一直在研究使用模型事件以便当我的品牌模型被恢复时,我可以得到图像并恢复它,然后在图像模型中有一个类似的事件来获得图像大小并恢复它们。我正在努力为这个品牌获取被删除的图片记录。这就是我在我的品牌模式中所尝试的:

/**
 * Model events
 */
protected static function boot() {
    parent::boot();

    /**
     * Logic to run before delete
     */
    static::deleting(function($brand) {
         $brand->image->delete();
    });

    /**
    * Logic to run before restore
    */
    static::restoring(function($brand) {
        $brand = Brand::withTrashed()->with('image')->find($brand->id);
        $brand->image->restore();
    });
}

I just get the following error message on the line that tries to restore the image:

我在试图恢复图像的行上得到如下错误消息:

Call to a member function restore() on a non-object

1 个解决方案

#1


4  

In your code you disable soft delete constraint on the query that fetches the brand, not the image. Try the following:

在你的代码中,你禁用了对查询的软删除约束,而不是图像。试试以下:

static::restoring(function($brand) {
  $brand->image()->withTrashed()->first()->restore();
});

Please note that there is no need to fetch the $brand object as it's passed to the restoring callback automatically.

请注意,不需要获取$brand对象,因为它被自动传递到restore callback。

#1


4  

In your code you disable soft delete constraint on the query that fetches the brand, not the image. Try the following:

在你的代码中,你禁用了对查询的软删除约束,而不是图像。试试以下:

static::restoring(function($brand) {
  $brand->image()->withTrashed()->first()->restore();
});

Please note that there is no need to fetch the $brand object as it's passed to the restoring callback automatically.

请注意,不需要获取$brand对象,因为它被自动传递到restore callback。