我有以下代码提供以下异常,我无法弄清楚原因,任何帮助都将不胜感激。
参数号无效:绑定变量数不匹配 令牌数量
if (!empty($ids)) {
$queryIds = implode(",", $ids);
$query = $em->createQueryBuilder()
->from('MainClientBundle:Posts','p')
->select('p')
->where('p.id >= :rand')
->where('p.id NOT IN (:ids)')
->orderBy('p.id','ASC')
->setParameter('rand', rand(1, $max))
->setParameter('ids', $queryIds)
->setMaxResults(1);
} else {
$query = $em->createQueryBuilder()
->from('MainClientBundle:Posts','p')
->select('p')
->where('p.id >= :rand')
->orderBy('p.id','ASC')
->setParameter('rand', rand(1, $max))
->setMaxResults(1);
}
try {
if($options['videos'] == "off"){
$query->where("p.type <> :type")->setParameter("type",1);
}
if($options['sfw'] == "on"){
$query->where("p.safeForWork <> :sfw")->setParameter("sfw",0);
}
$post = $query->getQuery()->getSingleResult();
} catch (\Doctrine\Orm\NoResultException $e) {
$post = null;
}
答案 0 :(得分:1)
您的第一个问题就是问题。您的查询应如下所示
if (!empty($ids)) {
$queryIds = implode(",", $ids);
$query = $em->createQueryBuilder()
->from('MainClientBundle:Posts','p')
->select('p')
->where('p.id >= :rand')
->andWhere('p.id NOT IN (:ids)')
->orderBy('p.id','ASC')
->setParameter('rand', rand(1, $max))
->setParameter('ids', $queryIds)
->setMaxResults(1);
} else {
$query = $em->createQueryBuilder()
->from('MainClientBundle:Posts','p')
->select('p')
->where('p.id >= :rand')
->orderBy('p.id','ASC')
->setParameter('rand', rand(1, $max))
->setMaxResults(1);
}
try {
if($options['videos'] == "off"){
$query->where("p.type <> :type")->setParameter("type",1);
}
if($options['sfw'] == "on"){
$query->where("p.safeForWork <> :sfw")->setParameter("sfw",0);
}
$post = $query->getQuery()->getSingleResult();
} catch (\Doctrine\Orm\NoResultException $e) {
$post = null;
}
请注意,我改变了你在哪里和哪里。在同一查询构建器中使用两个where()时,第一个将被第二个覆盖。
答案 1 :(得分:0)
正如上面评论中所述,问题在于->where
在查询构建器中的双重用法。如果您想要合并多个where子句,则需要使用->andWhere
或/和->orWhere
。
此外,我将结果更改为->getOneOrNullResult()
,因此您不需要使用用于捕获教义异常的整个try / catch块。
if (!empty($ids)) {
$queryIds = implode(",", $ids);
$query = $em->createQueryBuilder()
->from('MainClientBundle:Posts','p')
->select('p')
->where('p.id >= :rand')
->where('p.id NOT IN (:ids)')
->orderBy('p.id','ASC')
->setParameter('rand', rand(1, $max))
->setParameter('ids', $queryIds)
->setMaxResults(1);
} else {
$query = $em->createQueryBuilder()
->from('MainClientBundle:Posts','p')
->select('p')
->where('p.id >= :rand')
->orderBy('p.id','ASC')
->setParameter('rand', rand(1, $max))
->setMaxResults(1);
}
if($options['videos'] == "off"){
$query->where("p.type <> :type")->setParameter("type",1);
}
if($options['sfw'] == "on"){
$query->where("p.safeForWork <> :sfw")->setParameter("sfw",0);
}
$post = $query->getQuery()->getOneOrNullResult();