public function getRoles()
{
$roles = array();
// Checking that the user has permissions attached
if ($this->getPermissions() !== null)
{
// Looping on the permissions
foreach($this->getPermissions() as $permission)
{
// Checking that the permission has roles attached
if ($permission->getRoles() !== null)
{
// Looping on the roles for each permission
foreach($permission->getRoles() as $role)
{
$roles[] = $role->getName();
}
}
}
}
return $roles;
}
更好的解决方案是创建一个 UserManager 服务并通过 Doctrine Query Builder 获取角色(减少对数据库的调用):
/** @var EntityManager $this->em */
$roles = $this->em->createQueryBuilder()
->select('r')
->from('AcmeBundle:Role', 'r')
->innerJoin('r.permissions', 'p')
->innerJoin('p.users', 'u')
->where('u = :user')
->setParameter(':user', $user)
->getQuery()
->getResult()
;