我在使用全局范围时遇到问题,尤其是范围的删除。
在我的用户模型中,我有一个 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/