我需要用symfony执行下一个查询:
$qb = $this->_em;
$query = $qb->createQuery(
'SELECT f1.friend1
FROM AppBundle:Friend f1
WHERE f1.friend2 = ?1
UNION
SELECT f2.friend2
FROM AppBundle:Friend f2
WHERE f2.friend1 = ?2
'
)->setParameters(array(1 => $user_id, 2 => $user_id));
当我执行此$query
时,我遇到此错误:Expected end of string, got 'UNION'
。
我该怎么办?
编辑我的新代码:
$rsm = new \Doctrine\ORM\Query\ResultSetMapping();
$rsm->addEntityResult('Project\MyBundle\Entity\Friend', 'f');
$rsm->addFieldResult('f', 'friend1', 'friend1');
$rsm->addFieldResult('f', 'friend2', 'friend2');
$rsm->addFieldResult('f', 'id', 'id');
$rsm->addFieldResult('f', 'state', 'state');
$sql = "SELECT f1.friend1 AS friend
FROM friend f1
WHERE f1.friend2 = ?
UNION
SELECT f2.friend2 AS friend
FROM friend f2
WHERE f2.friend1 = ?";
$result = $this->_em->createNativeQuery($sql, $rsm)
->setParameter(1, $user_id)
->setParameter(2, $user_id)
->getResult();
return $result;
这是我的新查询。我直接在phpmyadmin上测试了这个查询,我有一个返回。但是使用这段代码,我在$ result中空了
答案 0 :(得分:1)
UNION
,而是可以使用Doctrine\ORM\Query\ResultSetMapping;这会将结果集映射到您定义为由$rsm->addEntityResult('Namespace\yourBundle\Entity\Friend', 'f');
$rsm = new \Doctrine\ORM\Query\ResultSetMapping();
$rsm->addEntityResult('Namespace\yourBundle\Entity\Friend', 'f');
$rsm->addFieldResult('f', 'friend', 'friend1');
$sql = "SELECT f1.friend1 AS friend
FROM friend_table f1
WHERE f1.friend2 = ?
UNION
SELECT f2.friend2 AS friend
FROM friend_table f2
WHERE f2.friend1 = ?";
$result = $DM->createNativeQuery($sql, $rsm)
->setParameter(1, $user_id)
->setParameter(2,$user_id)
->getResult();
根据评论进行修改
<小时/> 由于缺乏使用union的信息而不是明智的解决方案,但在下面的评论中您可以这样做以映射字段,但请记住这将为您提供重复
$rsm = new \Doctrine\ORM\Query\ResultSetMapping();
$rsm->addEntityResult('Project\MyBundle\Entity\Friend', 'f');
$rsm->addFieldResult('f', 'friend1', 'friend1');
$rsm->addFieldResult('f', 'friend2', 'friend2');
$rsm->addFieldResult('f', 'id', 'id');
$rsm->addFieldResult('f', 'state', 'state');
$sql = "SELECT f1.id,f1.friend1 AS friend,f1.friend1,f1.friend2 ,f1.state
FROM friend f1
WHERE f1.friend2 = ?
UNION
SELECT f2.id,f2.friend2 AS friend,f2.friend1,f2.friend2 ,f2.state
FROM friend f2
WHERE f2.friend1 = ?";
$result = $this->_em->createNativeQuery($sql, $rsm)
->setParameter(1, $user_id)
->setParameter(2, $user_id)
->getResult();
编辑2 我只想要一个包含一个字段“friend”的数组,其中一个是friend1,另一个是friend2
对于上述内容,您要求使用实体
运行两个查询$DM = $this->getDoctrine()->getEntityManager();
$result1=$DM->getRepository('Namespace\yourBundle\Entity\Friend')
->findBy(array('friend2'=>$user_id));
$result2=$DM->getRepository('Namespace\yourBundle\Entity\Friend')
->findBy(array('friend1'=>$user_id));