【问题标题】:How to disable soft deletes in Laravel 5.8 Eloquent model如何在 Laravel 5.8 Eloquent 模型中禁用软删除
【发布时间】:2019-07-11 04:53:28
【问题描述】:

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

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

【问题讨论】:

  • 出于好奇,您为什么要完全删除记录?
  • @usrNotFound,我将不得不插入和删除多条记录(不能简单地更改它们,太复杂的逻辑)。这些记录不需要软删除,将删除的记录保留在数据库中会浪费太多磁盘空间
  • 我认为$modal->forceDelete() 会工作
  • 这是一个选项,但如果我想删除这些对象以及其他一些可软删除的对象,我会做一些特殊的处理

标签: laravel oop laravel-5 eloquent soft-delete


【解决方案1】:

你应该做两件事:

  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 字段设置为true:
    protected $forceDeleting = true;

因此,您可以禁用软删除行为,同时仍扩展使用 SoftDeletes 特征的 BaseModel。

【讨论】:

    【解决方案2】:

    如果您使用softDelete trait 但不想在特定查询中使用它,那么您可以在模型中使用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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-06
      • 1970-01-01
      • 2020-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-28
      相关资源
      最近更新 更多