繁体   English   中英

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

[英]How to disable soft deletes in Laravel 5.8 Eloquent model

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

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

你应该做两件事:

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

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

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

因此,您可以禁用软删除的行为,同时还延长BaseModel它使用SoftDeletes特质。

如果您正在使用softDelete特征但不想在特定查询中使用它,那么您可以在模型中使用withoutGlobalScope方法。

User::withoutGlobalScope(Illuminate\Database\Eloquent\SoftDeletingScope::class)->get();

如果您想对特定查询使用多个模型,那么最好在AppServiceProvider扩展 eloquent builder

public function boot()
{
   Builder::macro('withoutSoftDeletingScope', function () {
     $this->withoutGlobalScope(Illuminate\Database\Eloquent\SoftDeletingScope::class);

       return $this;
    });
 }

然后你可以在任何模型中作为方法调用

User::withoutSoftDeletingScope()->get();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM