我的克星有问题:SQL / DQL 我有一个实体:风格和实体投票。风格可以有很多投票(你可以想象),一个投票只与一个风格相关联。
我现在想要搜索投票少于特定金额的样式(它的用户输入,但让我们说它是5)。这是我与 querybuilder
一起使用的代码$qb = $this->createQueryBuilder('s');
$qb
->select("s")
->join('s.votes', 'v')
->addSelect("COUNT(v.id) as voteCount")
->where("voteCount < ?1")
->orderBy('voteCount', "DESC")
->setMaxResults(3)
->setFirstResult(0)
->groupBy('s.id')
->setParameter(1, 5);
$query = $qb->getQuery();
$result = $query->getResult();
一旦我尝试执行查询,它基本上说,我在where子句中不知道我的voteCount。这是确切的错误消息
执行&#39; SELECT时出现异常s0_.active AS active0,s0_.views AS views1,s0_.description AS description2,s0_.name AS name3,s0_.id AS id4,s0_.updated AS updated5,s0_ .created AS created6,COUNT(v1_.id)AS sclr7,s0_.battle_id AS battle_id8,s0_.user_id AS user_id9,s0_.voucher_id AS voucher_id10 FROM Style s0_ INNER JOIN Vote v1_ ON s0_.id = v1_.style_id WHERE sclr7&lt; ? GROUP BY s0_.id ORDER BY sclr7 DESC LIMIT 3 OFFSET 0&#39;用params [1]:
SQLSTATE [42S22]:未找到列:1054未知列&#39; sclr7&#39;在&#39; where子句&#39;
我做错了什么?我怎样才能搜索voteCount?
答案 0 :(得分:2)
sum
和count
等汇总函数的条件应放在having
子句中。
$qb = $this->createQueryBuilder('s');
$qb->select("s");
$qb->join('s.votes', 'v');
$qb->addSelect("COUNT(v.id) as voteCount");
$qb->orderBy('voteCount', "DESC");
$qb->setMaxResults(3);
$qb->setFirstResult(0);
$qb->groupBy('s.id');
$qb->having("count(v.id) < ?1"); //changed from where
$qb->setParameter(1, 5);
$query = $qb->getQuery();
$result = $query->getResult();
答案 1 :(得分:0)
您不能在WHERE子句中引用列别名。
更改
$qb->where("voteCount < ?1");
要
$qb->where("COUNT(v.id) < ?1");