我在symfony上使用这个原生SQL查询(这是一个非常糟糕的做法),但是我很难让它在没有触发多个错误的情况下使用DQL运行。
SELECT Image.path, Image.name
FROM Image
LEFT JOIN ImageVoters ON Image.id = ImageVoters.image_id
WHERE ImageVoters.voter_id =1
AND ImageVoters.action = 'favourite'
ORDER BY Image.created_at ASC
这是我到目前为止所得到的
public function findMyFavourites()
{
return $this->getEntityManager()
->createQuery('SELECT p.path,p.name
FROM GabrielUploadBundle:Image p
LEFT JOIN GabrielUploadBundle:ImageVoters v
ON p.id = v.image_id
WHERE v.action ="favourite"
ORDER BY p.created_at ASC')
->getResult();
}
出于某种原因抛出此错误
错误:预期的Doctrine \ ORM \ Query \ Lexer :: T_WITH,“开启”
这是可行的查询
$em = $this->getDoctrine()->getManager();
$query = $em->getRepository('GabrielUploadBundle:Image')->createQueryBuilder('p')
->select(array('p.path', 'p.name','p.id','p.upvotes','p.imageowner','p.createdAt','p.updatedAt'))
->leftJoin('GabrielUploadBundle:ImageVoters', 'v', 'WITH', 'p.id = v.image_id')
->where("v.action = 'favourite'")
->andWhere("v.voter_id = 1")
->orderBy('p.createdAt', 'ASC')
->getQuery();
答案 0 :(得分:2)
如果您将ON
更改为WITH
,您的查询就可以了
你也可以尝试
$query = $em->getRepository('GabrielUploadBundle:Image')->createQueryBuilder('p')
->select(array('p.path', 'p.image'))
->leftJoin('GabrielUploadBundle:ImageVoters', 'v', 'WITH', 'p.id = v.image_id')
->where("v.action = 'favourite'")
->orderBy('p.createdAt', 'ASC')
->getQuery();
$result = $query->getResult();
答案 1 :(得分:0)
另外,如果Image Entity类中的Image模型和ImageVoters模型之间存在关系,您可以这样做:
->leftJoin('p.imageVoters', 'v')
学说将为你做其余的事。