如何使用dql获取未连接的值? 这段代码中的问题是我只收到有评论的帖子..
public function getAllPostsDQL()
{
$q = $this->getEntityManager()
->createQuery('SELECT p.type,p.date,p.urlImage,p.nom,u.nom as nomU,u.prenom as prenomU ,COUNT(co) as nb,MAX(co.date) as maxDate FROM PidevBundle:Publication p LEFT OUTER JOIN
PidevBundle:Commentaire co WITH co.idPublication=p
JOIN PidevBundle:User u WITH p.idUser=u
');
return $q->getResult();
}
答案 0 :(得分:1)
试试这个:(可能需要更改Symfony3语法)
public function getAllPostsDQL()
{
$qb = $this->createQueryBuilder('publication');
$qb->select(array('publication.type', 'publication.date', 'publication.urlImage',
'publication.nom', 'u.nom AS nomU', 'u.prenom AS prenomU',
'COUNT(co.id) AS nb', 'MAX(co.date) AS maxDate'))
->leftJoin('p.idUser', 'u')
->leftJoin('p.idCommentaire', 'co');
return $qb->getQuery()->getResult();
}
答案 1 :(得分:0)
尝试这样的事情:
public function getAllPostsDQL()
{
$q = $this->getEntityManager()->createQuery(
'SELECT
p.type,
p.date,
p.urlImage,
p.nom,
u.nom as nomU,
u.prenom as prenomU,
COUNT(co.id) as nb,
MAX(co.date) as maxDate
FROM PidevBundle:Publication p
LEFT JOIN p.idUser u
LEFT JOIN PidevBundle:Commentaire co ON co.id = u.id
');
return $q->getResult();
}
答案 2 :(得分:-1)
我终于找到了解决方案,虽然我认为它是垃圾代码:/ 谢谢大家。 代码:
public function getAllPostsDQL()
{
$q = $this->getEntityManager()->createQuery(
'SELECT
p.type,
p.date,
p.urlImage,
p.nom,
u.nom as nomU,
u.prenom as prenomU,
(SELECT COUNT(co.id) FROM PidevBundle:Commentaire co WHERE co.idPublication=p) as nb,
(SELECT MAX(com.date) FROM PidevBundle:Commentaire com WHERE com.idPublication=p) as maxDate
FROM PidevBundle:Publication p
INNER JOIN p.idUser u
');
return $q->getResult();
}