我正在尝试删除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,为了确保方法被调用,我记录了SQL查询,并看到调用了4,但没有调用之前的3(准确地说,这些方法没有删除users.deleted_at is null部件)。我分别试了一下,也试了一下。
我知道我可以做这样的$users = User::withTrashed()->get();,它是有效的,但这并不是完全安全的,因为我必须找到每个可以查询用户的位置,并将其封装在一个if语句中。
发布于 2017-02-23 19:06:48
我不知道有什么比用下面这样的东西覆盖SoftDeletes特征中的bootSoftDeletes()更容易的解决方案:
public static function bootSoftDeletes()
{
if (!Auth::check() || !Auth::user()->hasRole('cpo')) {
static::addGlobalScope(new SoftDeletingScope);
}
}动态添加和删除全局作用域有时会产生一些奇怪的行为:/
发布于 2021-04-06 19:26:42
此解决方案根据条件删除作用域。防止调用未定义的方法错误,这些错误是我使用接受的答案得到的。
<?php namespace App\Scopes;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\SoftDeletingScope;
/**
* Class UserScope
*
* @package App\Scopes
*/
class UserScope implements Scope
{
/**
* @param Builder $builder
* @param Model $model
*/
public function apply(Builder $builder, Model $model)
{
if (optional(auth()->user())->is_admin) $builder->withoutGlobalScope(SoftDeletingScope::class);
}
}为了使其正常工作,我必须确保在调用models父引导方法之前添加了作用域。
https://stackoverflow.com/questions/42411414
复制相似问题