在 Symfony2 中使用 JOIN 标准的 findBy
我有 3 个简单的表:用户、角色、具有多对多关系的 user_x_role.我有 2 个实体:用户和角色.用户实体具有带有关系注释的 $userRoles 属性.在控制器中,我需要获取所有具有特定角色的用户.但我不知道如何在控制器中使用 JOIN.当前错误代码:
I have 3 simple tables: user, role, user_x_role with Many-To-Many relation. I have 2 entities: User and Role. User entity has $userRoles property with relation annotation. In Controller I need to fetch all users with specific role. But I don't know how to use JOIN in controller. Current wrong code:
$role = $this->getDoctrine()->getRepository('TestBackEndBundle:Role');
$roles = $role->findBy(array('name' => 'ROLE_PARTNER'));
$user = $this->getDoctrine()->getRepository('TestBackEndBundle:User');
$partners = $user->findBy(array('userRoles' => $roles));
它抛出未定义的索引:joinColumns in ...".但我在用户实体中有 joinColumns:
It thows "Undefined index: joinColumns in ...". But I have joinColumns in User entity:
/**
* @ORMManyToMany(targetEntity="Role")
* @ORMJoinTable(name="user_x_role",
* joinColumns={@ORMJoinColumn(name="user_id", referencedColumnName="id", onDelete="CASCADE", onUpdate="CASCADE")},
* inverseJoinColumns={@ORMJoinColumn(name="role_id", referencedColumnName="id", onDelete="CASCADE", onUpdate="CASCADE")}
* )
* @var ArrayCollection
*/
protected $userRoles;
推荐答案
IMO 最好的方法是为用户实体创建自己的存储库.然后在该存储库中创建诸如getUsersByRole"之类的方法,您可以在其中使用查询构建器进行所需的查询.
IMO the best way for it is create your own repository for User entity. Then in that repository create method like "getUsersByRole" where you make the query you want with query builder.
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->select('u')
->from('
amespaceforUser', 'u')
->join('u.roles', 'r')
->where(...)
return $qb->getQuery()->getResult();
相关文章