FOS 捆绑包 - 如何选择具有特定角色的用户? [英] FOS bundle - How to select users with a specific role?
本文介绍了FOS 捆绑包 - 如何选择具有特定角色的用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 FOS 包,我想从数据库中检索具有给定角色的所有用户.
I am using the FOS bundle and I want to retrieve all users with a given ROLE from the database.
最好的方法是什么?
推荐答案
只需将此添加到您的 UserRepository 或将 $this->_entityName
替换为 YourUserBundle:User
:
Just add this in your UserRepository or replace $this->_entityName
by YourUserBundle:User
:
/**
* @param string $role
*
* @return array
*/
public function findByRole($role)
{
$qb = $this->_em->createQueryBuilder();
$qb->select('u')
->from($this->_entityName, 'u')
->where('u.roles LIKE :roles')
->setParameter('roles', '%"'.$role.'"%');
return $qb->getQuery()->getResult();
}
如果您使用 FOSUser Groups,您应该使用:
If you are using FOSUser Groups you should use:
/**
* @param string $role
*
* @return array
*/
public function findByRole($role)
{
$qb = $this->_em->createQueryBuilder();
$qb->select('u')
->from($this->_entityName, 'u')
->leftJoin('u.groups', 'g')
->where($qb->expr()->orX(
$qb->expr()->like('u.roles', ':roles'),
$qb->expr()->like('g.roles', ':roles')
))
->setParameter('roles', '%"'.$role.'"%');
return $qb->getQuery()->getResult();
}
这篇关于FOS 捆绑包 - 如何选择具有特定角色的用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文