我想创建一个查询,在关闭的位置调用同一个表中的最新日期。
$query = $this->createQueryBuilder('a')
->select('a.amount')
->where('a.product = :productId')
->andWhere('a.id = :id'),
$recentDate = null;
if($date === null){
$recentDate = $this->createQueryBuilder('a')
->select($query->expr()->max('a.date'))->getQuery()->getResult();
$query->andWhere('a.date = :recentDate');
}else{
$query->andWhere('a.date = :date');
}
$query->setParameters(array(
'productId' => $productId,
'id' => $id,
'date' => $date,
'recentDate' => $recentDate,
));
return $query;
但我有这个问题:
Invalid parameter number: number of bound variables does not match number of tokens
答案 0 :(得分:2)
只需将您的“日期”参数和“recentDate”参数命名为同名,它们就不能同时出现在您的请求中,只会在setParameters()
$query = $this->createQueryBuilder('a')
->select('a.amount')
->where('a.product = :productId')
->andWhere('a.id = :id')
->andWhere('a.date = :date');
if($date === null){
$date = $this->createQueryBuilder('a')
->select($query->expr()->max('a.date'))->getQuery()->getResult();
}
$query->setParameters(array(
'productId' => $productId,
'id' => $id,
'date' => $date
));
return $query;
答案 1 :(得分:1)
试试这个:
$query->setParameters(array(
'productId' => $productId,
'id' => $id
));
if($date === null) {
$query->setParameter(':recentDate', $recentDate);
} else {
$query->setParameter(':date', $date);
}
如果$ date!= null,则recentDate参数不是查询的一部分,反之亦然,因此不是日期参数。
也许有更优雅的方式来构建此查询?
亲切的问候 乔答案 2 :(得分:1)
您为只有3的查询提供了4个参数。
$query = $this->createQueryBuilder('a')
->select('a.amount')
->where('a.product = :productId')
->andWhere('a.id = :id'),
$recentDate = null;
if($date === null){
$recentDate = $this->createQueryBuilder('a')
->select($query->expr()->max('a.date'))->getQuery()->getResult();
$query->andWhere('a.date = :recentDate');
}else{
$query->andWhere('a.date = :date');
}
$query->setParameters(array(
'productId' => $productId,
'id' => $id,
));
if($date === null){
$query->setParameter('recentDate', $recentDate);
}else{
$query->setParameter('date', $date);
}