2017-02-23 151 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