首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将SoftDeletingScope作为全局作用域删除

将SoftDeletingScope作为全局作用域删除
EN

Stack Overflow用户
提问于 2017-02-23 17:15:34
回答 2查看 1.2K关注 0票数 3

我正在尝试删除SoftDeletingScope作为特定用户角色的全局作用域。所以它应该看起来像这样:

代码语言:javascript
复制
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语句中。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-02-23 19:06:48

我不知道有什么比用下面这样的东西覆盖SoftDeletes特征中的bootSoftDeletes()更容易的解决方案:

代码语言:javascript
复制
public static function bootSoftDeletes()
{
    if (!Auth::check() || !Auth::user()->hasRole('cpo')) {
        static::addGlobalScope(new SoftDeletingScope);
    }
}

动态添加和删除全局作用域有时会产生一些奇怪的行为:/

票数 1
EN

Stack Overflow用户

发布于 2021-04-06 19:26:42

此解决方案根据条件删除作用域。防止调用未定义的方法错误,这些错误是我使用接受的答案得到的。

代码语言:javascript
复制
<?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父引导方法之前添加了作用域。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42411414

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档