php - Laravel:如何将 "disable"设为全局范围以便将 "inactive"对象包含到查询中?

标签 php laravel eloquent

我在使用全局范围时遇到问题,尤其是范围的删除。

在我的用户模型中,我有一个 ActivatedUsersTrait,它引入了一个全局范围以仅查询列“activated”设置为 true 的用户(用户在电子邮件验证后被“激活”)。

到目前为止一切正常,当我查询 User::all() 时,我只获得 activated=true 的用户。

我现在的问题是,如何将未激活的用户包含到我的查询中,就像 SoftDeletingTrait 通过 withTrashed() 所做的那样?这仅与我的 ActivationController 相关,我需要在其中获取用户、设置 activated=true 并将它们保存回数据库。

我已经在我的 ActiveUsersTrait 中创建了一个 withInactive() 方法,基于我在 SoftDeletingTrait 中找到的方法,但是当我在 User::withInactive->get() 上运行查询时,未激活的用户不会显示在结果中。

这是我的 ActiveUsersTrait:

use PB\Scopes\ActiveUsersScope;

trait ActiveUsersTrait {

    public static function bootActiveUsersTrait()
    {
        static::addGlobalScope(new ActiveUsersScope);
    }

    public static function withInactive()
    {
        // dd(new static);
        return (new static)->newQueryWithoutScope(new ActiveUsersScope);
    }

    public function getActivatedColumn()
    {
        return 'activated';
    }

    public function getQualifiedActivatedColumn()
    {
        return $this->getTable().'.'.$this->getActivatedColumn();
    }

}

和我的 ActiveUsersScope:

use Illuminate\Database\Eloquent\ScopeInterface;
use Illuminate\Database\Eloquent\Builder;

class ActiveUsersScope implements ScopeInterface {

    public function apply(Builder $builder)
    {
        $model = $builder->getModel();

        $builder->where($model->getQualifiedActivatedColumn(), true);

    }

    public function remove(Builder $builder)
    {
        $column = $builder->getModel()->getQualifiedActivatedColumn();

        $query = $builder->getQuery();

        foreach ((array) $query->wheres as $key => $where)
        {
            if ($this->isActiveUsersConstraint($where, $column))
            {
                unset($query->wheres[$key]);

                $query->wheres = array_values($query->wheres);
            }
        }
    }

    protected function isActiveUsersConstraint(array $where, $column)
    {
        return $where['type'] == 'Basic' && $where['column'] == $column;
    }
}

非常感谢任何帮助!

提前致谢! -约瑟夫

最佳答案

Eloquent 查询现在有一个 removeGlobalScopes() 方法。

参见:https://laravel.com/docs/5.3/eloquent#query-scopes (在删除全局范围子标题下)。

来自文档:

// Remove one scope
User::withoutGlobalScope(AgeScope::class)->get();

// Remove all of the global scopes...
User::withoutGlobalScopes()->get();

// Remove some of the global scopes...
User::withoutGlobalScopes([
    FirstScope::class, SecondScope::class
])->get();

关于php - Laravel:如何将 "disable"设为全局范围以便将 "inactive"对象包含到查询中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25312386/

相关文章:

php - Woocommerce - 如何从外部脚本添加产品变体

php - 最近PHPMAILER停止发送邮件

php - Laravel 在一个查询中选择不同的内容

php - iframe 中的 laravel 应用程序不断刷新 session

mysql - Laravel lockForUpdate + 事务

php - Eloquent 查询 1 :n relationship

php - Laravel 数据库查询返回错误值

php - 给出警告 : mysqli_query() expects at least 2 parameters, 1。什么?

laravel - 如何将laravel vue站点部署到共享主机

php - 加载具有不同外部值的相同模态 - 使用 jquery 传递变量