我在Symfony2中遇到一些问题,我有3个问题(它们有点简化):
class Group
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @var string
*
* @ORM\Column(name="name", type="string", length=255)
*/
protected $name;
/** @ORM\OneToMany(targetEntity="GroupMember", mappedBy="family") */
protected $groupMembers;
class GroupMember
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\Column(name="group_member_type", type="integer")
*/
protected $groupMemberType;
/**
* @ORM\ManyToOne(targetEntity="Group", inversedBy="groupMembers")
* @ORM\JoinColumn(name="group_id", referencedColumnName="id", nullable=false)
*/
protected $group;
/**
* @ORM\ManyToOne(targetEntity="Test\UserBundle\Entity\User", inversedBy="memberships")
* @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false)
*/
protected $user;
USER - >标准FOSuserbundle用户
我想进行查询,返回当前用户为组成员的所有组。有人可以告诉我该怎么做吗?
这是我的尝试:
SELECT g FROM (group g INNER JOIN groupmember gm ON g.id=gm.group_id) INNER JOIN fos_user u ON gm.user_id = u.id WHERE u.id = 6
但它返回
Unknown column 'g' in 'field list'
答案 0 :(得分:3)
使用查询构建器,假设您已提取用户并将其存储在$userObject
中,而您的包名称为BundleName
:
$groups = $this->getDoctrine()->getManager()->createQueryBuilder()
->select('g')
->from('BundleName:Group', 'g')
->innerJoin('g.groupMembers', 'gm')
->innerJoin('gm.user', 'u')
->where('u = :user')
->setParameter('user', $userObject)
->getQuery()
->getResult();
您还需要确保关系映射是正确的。
/** @ORM\OneToMany(targetEntity="GroupMember", mappedBy="family") */
protected $groupMembers;
应该是
/** @ORM\OneToMany(targetEntity="GroupMember", mappedBy="group") */
protected $groupMembers;
答案 1 :(得分:0)
这是正确的查询:
SELECT g.* FROM (group g INNER JOIN groupmember gm ON g.id=gm.group_id) INNER JOIN fos_user u ON gm.user_id = u.id WHERE u.id = 6