在 Symfony2 中使用 JOIN 标准的 findBy [英] findBy with JOIN criteria in Symfony2

查看:23
本文介绍了在 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();

这篇关于在 Symfony2 中使用 JOIN 标准的 findBy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆