【问题标题】:How to always use withTrashed() for model Binding如何始终使用 withTrashed() 进行模型绑定
【发布时间】:2017-12-11 09:36:47
【问题描述】:

在我的应用程序中,我对很多对象使用了软删除,但我仍然想在我的应用程序中访问它们,只是显示一条特殊消息,表明该项目已被删除并有机会恢复它。

目前我必须为 RouteServiceProvider 中的所有路由参数执行此操作:

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {


        parent::boot();

        Route::bind('user', function ($value) {
            return User::withTrashed()->find($value);
        });

        Route::bind('post', function ($value) {
            return Post::withTrashed()->find($value);
        });

        [...]


    }

有没有更快更好的方法将垃圾对象添加到模型绑定?

【问题讨论】:

    标签: laravel eloquent laravel-5.5


    【解决方案1】:

    Jerodev 的回答对我不起作用。 SoftDeletingScope 继续过滤掉已删除的项目。所以我只是覆盖了那个范围和SoftDeletes trait:

    SoftDeletingWithDeletesScope.php:

    namespace App\Models\Scopes;
    
    use Illuminate\Database\Eloquent\Builder;
    use Illuminate\Database\Eloquent\Model;
    use Illuminate\Database\Eloquent\SoftDeletingScope;
    
    class SoftDeletingWithDeletesScope extends SoftDeletingScope
    {
        public function apply(Builder $builder, Model $model)
        {
        }
    }
    

    SoftDeletesWithDeleted.php:

    namespace App\Models\Traits;
    
    use Illuminate\Database\Eloquent\SoftDeletes;
    use App\Models\Scopes\SoftDeletingWithDeletesScope;
    
    trait SoftDeletesWithDeleted
    {
        use SoftDeletes;
    
        public static function bootSoftDeletes()
        {
            static::addGlobalScope(new SoftDeletingWithDeletesScope);
        }
    }
    

    这实际上只是删除了过滤器,同时仍然允许我使用所有其余的 SoftDeletingScope 扩展。

    然后在我的模型中,我用我的新 SoftDeletesWithDeleted 特征替换了 SoftDeletes 特征:

    use App\Models\Traits\SoftDeletesWithDeleted;
    
    class MyModel extends Model
    {
        use SoftDeletesWithDeleted;
    

    【讨论】:

      【解决方案2】:

      您可以将Global Scope 添加到即使被丢弃也必须可见的模型。

      例如:

      class WithTrashedScope implements Scope
      {
          public function apply(Builder $builder, Model $model)
          {
              $builder->withTrashed();
          }
      }
      
      class User extends Model
      {
          protected static function boot()
          {
              parent::boot();
      
              static::addGlobalScope(new WithTrashedScope);
          }
      }
      

      更新:
      如果您不想显示已删除的对象,您仍然可以手动将->whereNull('deleted_at') 添加到您的查询中。

      【讨论】:

      • 这会使软删除无关紧要,我可以删除 softDelete 特征,但随后,我的软删除对象将始终是 shawn。例如,我想显示我所有活跃用户的列表,或者对他们进行自动完成,我不想显示软删除。我只希望它们在模型绑定中,因此在对它们进行请求时不会收到 404
      猜你喜欢
      • 1970-01-01
      • 2010-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-24
      • 1970-01-01
      • 2021-03-04
      • 2022-01-09
      相关资源
      最近更新 更多