如何在 Laravel 5.8 Eloquent 模型中禁用软删除

vvm*_*mul 3 oop soft-delete laravel eloquent laravel-5

在我的项目中,所有模型都扩展了BaseModel类,SoftDeletes默认情况下使用trait。但在某些特定情况下,例如在课堂上,ShouldHardDelete我不希望我的数据库记录被软删除。让我们假设,我不能否认扩展BaseModel.

我应该在我的ShouldHardDelete班级中进行哪些更改以防止它使用软删除?

vvm*_*mul 8

你应该做两件事:

  1. 有一个静态方法bootSoftDeletes()SoftDeletes特点,它初始化软删除行为模型:
    /**
     * Boot the soft deleting trait for a model.
     *
     * @return void
     */
    public static function bootSoftDeletes()
    {
        static::addGlobalScope(new SoftDeletingScope);
    }
Run Code Online (Sandbox Code Playgroud)

ShouldHardDelete类中将其覆盖为空方法:

    /**
     * Disable soft deletes for this model
     */
    public static function bootSoftDeletes() {}
Run Code Online (Sandbox Code Playgroud)
  1. $forceDeleting字段设置为truein ShouldHardDelete
    protected $forceDeleting = true;
Run Code Online (Sandbox Code Playgroud)

因此,您可以禁用软删除行为,同时仍然扩展BaseModelwhich 使用SoftDeletestrait。