以下是短篇小说:
我有3张桌子(1张适合多种关系),这是新闻和俱乐部。
新闻可能与很多俱乐部有关。它也可能没有关系。
例如;我有3个俱乐部的消息。所以,我必须选择我的形式的俱乐部。 另一个例子;我有一般公众的新闻。所以,我们不会选择任何俱乐部。
因此;我想用singleScalarResult计算非相关记录。
以下是我获取结果的查询:
// Get entity manager
$em = $this->getDoctrine()->getManager();
// Create query builder
$qb = $em->createQueryBuilder();
$qb
->select('n')
->from('ATLClubBundle:News', 'n')
->where(
$qb->expr()->isNull('n.deletedAt'),
$qb->expr()->eq("n.newsType", ":type")
)
->setParameter("type", $newsType);
if (!$slug) {
// if there is no slug choose both relational and non-relational news
} else if($slug == 'district') {
// if slug is defined and slug is district get only non-relational news. This is working well with using having but if there any better way to do it, please let me know.
$qb
->leftJoin("n.clubs", "c")
->andWhere(
$qb->expr()->eq('n.showAll', 1)
)
->having('COUNT(c.id) = 0')
->groupBy('n.id');
} else {
// else, just get related news with clubs.
$qb->innerJoin("n.clubs", "c");
}
$qb
->setFirstResult($offset)
->setMaxResults($limit);
此代码块可以很好地获取结果。
当我尝试计算分页结果时;
$counter = $em->createQueryBuilder();
$counter
->select('COUNT(n.id)')
->from('ATLClubBundle:News', 'n')
->where(
$counter->expr()->isNull('n.deletedAt')
);
if(!$slug) {
// same stuff as above
} else if($slug == 'district') {
$counter
->leftJoin("n.clubs", "c", "WITH")
->andWhere(
$counter->expr()->eq('n.showAll', 1)
);
// not working, throws exception with having or group by.
} else {
$counter->innerJoin("n.clubs", "c");
}
$result = $counter->getQuery()->getSingleScalarResult();
我收到错误(因为拥有或分组而引发异常)