我正在尝试获取没有所有者角色的特定于客户的用户,但它还会跳过没有任何角色的用户。用户可以具有一个或多个角色。我想让所有用户都具有多个角色或根本没有任何角色,但是如果用户包含所有者角色,则仅应忽略该用户。
注意:我正在使用spatie/laravel-permission
,它从具有模型中间表的角色中获取用户角色
这是我的范围查询
public function scopeForCompany(EloquentBuilder $query, string $customerId): EloquentBuilder
{
$query->where(function (EloquentBuilder $q) {
$q->doesntHave('roles');
$q->orHas('roles');
});
$query->whereHas('roles', function (EloquentBuilder $q) {
$q->whereNotIn('name', ['owner']);
});
return $query->where('customer_id', $customerId);;
}
这是测试
public function it_apply_query_scope_to_get_customer_specific_users_only(): void
{
$model = new User;
// create non customer users
\factory(User::class, 2)->create();
$customer = \factory(Customer::class)->create();
foreach (['owner', 'admin', 'user'] as $role) {
$role = \factory(Role::class)->create(['name' => $role]);
$user = \factory(User::class)->create(['customer_id' => $customer->id]);
$user->roles()->save($role);
}
$scopedUsers = $model->newQuery()->forCompany($customer->id)->get();
$nonScopedUsers = $model->newQuery()->get();
static::assertCount(2, $scopedUsers); // Failed asserting that actual size 0 matches expected size 2.
static::assertCount(5, $nonScopedUsers);
}
调试:这是行查询:
"select * from `users` where (not exists (select * from `roles` inner join `model_has_roles` on `roles`.`id` = `model_has_roles`.`role_id` where `users`.`id` = `model_has_roles`.`model_uuid` and `model_has_roles`.`model_type` = ?) or exists (select * from `roles` inner join `model_has_roles` on `roles`.`id` = `model_has_roles`.`role_id` where `users`.`id` = `model_has_roles`.`model_uuid` and `model_has_roles`.`model_type` = ?)) and exists (select * from `roles` inner join `model_has_roles` on `roles`.`id` = `model_has_roles`.`role_id` where `users`.`id` = `model_has_roles`.`model_uuid` and `model_has_roles`.`model_type` = ? and `name` not in (?)) and `customer_id` = ? and `users`.`deleted_at` is null"
这是我首先尝试但没有奏效的
return $query->whereHas('roles', function (EloquentBuilder $query): void {
$query->whereNotIn('name', ['owner']);
})->where('customer_id', $customerId);
任何帮助将不胜感激
答案 0 :(得分:3)
您需要执行一些“或”逻辑才能使此操作发生。我将查询分为三部分。
声明:“我想让所有用户都具有多个角色”
$query->has('roles', '>=', 2);
接下来,您希望所有人都没有角色:“或根本没有角色”。
$query->doesntHave('roles');
最后,您的查询正确地过滤出角色不能成为所有者的位置。
$query->whereHas('roles', function (EloquentBuilder $query): void {
$query->whereNotIn('name', ['owner']);
})
使用sub where查询将所有内容放在一起进行类似的操作。要正确执行您想要的“或”逻辑。
$query->where(function($builder){
$builder->has('roles', '>=', 2);
$builder->whereHas('roles', function (EloquentBuilder $query): void {
$query->whereNotIn('name', ['owner']);
})
});
$builder->orDoesntHave('roles');
在伪逻辑语句中,这看起来类似于:
(roles.each.name != 'owner' && count(roles) >= 2) || empty(roles)
让我们看看这是否对您有帮助,否则请发布构建器的toSql()并找出答案。这是一个相当复杂的查询构建器逻辑。