2017-02-23 70 views
3

我试图删除SoftDeletingScope作为特定用户角色的全局范围。所以应该以某种方式是这样的:删除SoftDeletingScope作为全球范围

protected static function boot() 
{ 
    parent::boot(); 

    if (Auth::check()) { 
     // CPOs can see deleted users 
     if (Auth::user()->hasRole('cpo')) { 
      static::addGlobalScope('user-cpo-deleted', function(Builder $builder) { 
       // 1 
       $builder->withoutGlobalScope(Illuminate\Database\Eloquent\SoftDeletingScope::class); 
       // 2 
       $builder->withoutGlobalScopes(); 
       // 3 
       $builder->withTrashed(); 
       // 4 
       $builder->where('id', '>=', 1); 
      }); 
     } 
    } 
} 

我试图解决1-3和,以确保该方法被调用可言,4我记录的SQL查询,发现4是所谓的,但不是3之前(准确地说,这些方法并没有删除users.deleted_at is null部分)。我分别尝试了所有这些。

我知道我可以做类似$users = User::withTrashed()->get();的工作,但是这样做并不完全安全,因为我必须找到每个可以查询用户的位置,并将其包装在if语句中。

+0

我知道它听起来很愚蠢,但是你可以尝试链接诸如'$ builder-> method() - > method()等等的调用吗? – TheFallen

+0

感谢您的评论,但@devk的解决方案工作;) – Tim

回答

1

我不知道从SoftDeletes比覆盖bootSoftDeletes()简单的解决方案具有这样的特点:

public static function bootSoftDeletes() 
{ 
    if (!Auth::check() || !Auth::user()->hasRole('cpo')) { 
     static::addGlobalScope(new SoftDeletingScope); 
    } 
} 

添加和动态消除全球范围产生有时会出现一些奇怪的行为:/

+0

这对我来说很简单。如果在添加全局范围的同时删除所有全局范围,我认为没有什么可以实现的。 – Tim