问题描述
我有一个作用域,它根据用户角色以限制方式起作用,您可以将一组规则转发到限制数据库最终输出的作用域.
I have a scope which is acting in a limiting fashion depending on a user role in a way that you can forward a set of rules to the scope limiting the final output from the DB.
一个真正简化的角色限制示例:
A really simplified role limit example:
{
"first_name": "=foo%"
}
只会返回其 first_name
以 foo%
开头的记录,这实际上意味着我已禁止具有该角色的用户查看任何以< foo%
.
will only return records whose first_name
begins with foo%
, which effectively means that I have forbidden the user with that role to see any records which do not begin with foo%
.
此方法的问题在于,如果某人没有施加任何限制,他将看到所有内容.我知道这是一个正确的假设,但是如果没有施加任何限制,我想禁止所有操作,因此,如果创建了新角色,则它没有任何权利.
The issue with this approach is that if someone has no limits imposed, he will see everything. I am aware that this is a valid assumption, but I would like to forbid everything if there are no limits imposed, so that if new role is created, it has no rights whatsoever.
当前,我在这种情况下抛出异常:
Currently I am throwing an exception for this case:
public function apply(Builder $builder, Model $model)
{
$input = $this->getAuthValues(get_class($model));
if (count($input) < 1) {
throw new \Exception('No rights for you');
}
$jsonQuery = new JsonQuery($builder, $input); <-- class responsible for assembling the queries based on the input
$jsonQuery->search();
}
但这当然也不例外.在这种情况下,我希望返回空数组.
But this of course is no exception. I would like empty array to be returned in that case.
我可以使用某种方法优雅地退出范围并返回空结果,而无需随后实际执行查询吗?
Can I use some method to gracefully exit the scope together with an empty result, without actually executing the query afterwards?
推荐答案
我来到一个解决方案,使一个不可能的查询返回0个结果.
I came to a solution to make an impossible query which would return 0 results.
public function apply(Builder $builder, Model $model)
{
$input = $this->getAuthValues(get_class($model));
if (count($input) < 1) {
$builder->whereRaw('1 = 0');
return;
}
$jsonQuery = new JsonQuery($builder, $input);
$jsonQuery->search();
}
这篇关于优雅地退出Laravel范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!