限制关系的结果

时间:2015-02-25 09:28:07

标签: php symfony doctrine-orm

我有简单的表格帖子和评论,我正在查询:

$repository = $this->getDoctrine()
    ->getRepository('AppBundle:Post');

$query = $repository->createQueryBuilder('p')
    ->where('p.made = :made')
    ->setParameter('made', 1)
    ->leftJoin('p.comments', 'c')
    ->andWhere('c.isAdmin = :isAdmin')
    ->setParameter('isAdmin', 1)
    ->getQuery();

$results = $query->getResult();

foreach($results as $post) {
    echo $post->getId(); // this clause where (->where('p.made = :made')) working ok
    foreach($post->getComments() as $comments) {
       echo $comment->getId(); //this clause where (->andWhere('c.isAdmin = :isAdmin')) not working. This return all results
    }
}

那么如何在查询中使用子句与关系?

SQL:

SELECT 
  i0_.id AS id0, 
  i0_.made AS made1, 
  i0_.name AS name2, 
FROM 
  post i0_ 
  LEFT JOIN comment i1_ ON i0_.id = i1_.comment_id 
WHERE 
  i0_.made = ? 
  AND i1_.isAdmin = ?

1 个答案:

答案 0 :(得分:2)

让我们在您的请求中添加一个select方法:

$query = $repository->createQueryBuilder('p')
->select(["c", "p"])
->where('p.made = :made')
->setParameter('made', 1)
->leftJoin('p.comments', 'c')
->andWhere('c.isAdmin = :isAdmin')
->setParameter('isAdmin', 1)
->getQuery();

它更好吗?

这更好用,因为你指定水合整个物体而不仅仅是水滴。