我需要帮助将有效的SQL查询转换为createQueryBuilder
。我遇到的问题是我不知道如何在createQueryBuilder
中的SELECT
上进行LEFT JOIN
。
SELECT username, count(c.user_owner_id) as num_contact, a_g.name as
group_name
FROM `oro_user` as u
INNER JOIN `oro_user_access_group` as u_g on u.id=u_g.user_id
INNER JOIN `oro_access_group` as a_g on u_g.group_id=a_g.id
LEFT JOIN
(SELECT cc.user_owner_id
FROM `orocrm_contact` as cc
INNER JOIN`orocrm_contact_to_contact_grp` as cc_g on cc_g.contact_id=cc.id
INNER JOIN `orocrm_contact_group`
as c_g on cc_g.contact_group_id=c_g.id
WHERE c_g.label='New One' and cc.semester_contacted='2017A')
as c on u.id=c.user_owner_id
WHERE a_g.name='Full-timer' and u.enabled = 1 and u.gender='male'
GROUP BY u.id
ORDER BY num_contact
我有两个查询,我希望用户可以 LEFT JOIN
contact
$user = $this->em->getRepository('OroUserBundle:User')->createQueryBuilder('u')
->select('u.username')
->innerJoin('u.groups','g')
->andWhere('g.name = :group')
->setParameter('group', 'Full-timer')
->getQuery();
$contacts = $this->em->getRepository('OroContactBundle:Contact')->createQueryBuilder('c')
->select('c')
->innerJoin('c.groups','g')
->andWhere('g.label = :group')
->andWhere('c.semester_contacted = :sem')
->setParameter('group', 'New One')
->setParameter('sem', '2017A')
->setMaxResults(1)
->getQuery();
这是一个相当复杂的查询,由于ORM QueryBuilder比您的实体更接近您的实体,因此我不确定您是否只能将DQL"转储"到->join()
中。有效的DBAL QueryBuilder的好消息:
$dbalQueryBuilder
->from('user_table as u')
...
->join('u', '('.$otherDbalQueryBuilder->getSQL().')', 'c')
这是来自记忆的,所以可能有些不同,但是类似的东西。
,您可以获得所需的所有字段,但您不会获得任何实体。幸运的是,学说提供了使用ResultsetMapping从本机SQL构建实体的方法。
$userWithContacts = $entityManager->createNativeQuery(
$dbalQueryBuilder->getSQL(),
$yourResultSetMapping
);
我知道这将需要更多的代码,并且可能不像使用ORM QueryBuilder那样好,但是我发现这通常是处理需要以某种方式移植到Orm的现有查询的最佳方法。