7

我有以下型号;品牌、图像和 Image_size。品牌有一个图像,图像有多个 image_size。所有这些模型都使用软删除,删除方面很好。但是,如果我想恢复已删除的品牌,我还需要恢复相关的 image 和 image_size 模型。

我一直在研究使用模型事件,这样当我的品牌模型被恢复时,我可以获取图像并恢复它,然后我将在图像模型中进行类似的事件来获取图像大小并恢复它们。我正在努力为该品牌获取已删除的图像记录。这就是我想要在我的品牌模型中做的事情:

/**
 * 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();
    });
}

我只是在尝试恢复图像的行上收到以下错误消息:

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

1 回答 1

5

在您的代码中,您对获取品牌而不是图像的查询禁用软删除约束。尝试以下操作:

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

请注意,不需要获取 $brand 对象,因为它会自动传递给恢复回调。

于 2015-07-09T09:07:13.277 回答