我有简单的表Post和Comment,我正在进行查询:
$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
}
}
那么,在查询关系时,如何使用where子句呢?
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 = ?
让我们在您的请求中添加一个选择方法:
$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();
它更好吗?
这样做效果更好,因为您指定对整个对象进行水合,而不仅仅是Id。