KevinR KevinR - 5 months ago 16
PHP Question

Symfony Doctrine take the most recent date in where close

I would like to make a query which call the most recent date in the same table in a where close.

$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;


but I have this issue:

Invalid parameter number: number of bound variables does not match number of tokens

Answer

Just name your "date" parameter and "recentDate" parameter with the same name, they couldn't be in your request together and pass only this unique parameter in your setParameters()

$query = $this->createQueryBuilder('a')
    ->select('a.amount')
    ->where('a.product = :productId')
    ->andWhere('a.id = :id'),

$myDate = null;

if($date === null){
    $myDate = $this->createQueryBuilder('a')
        ->select($query->expr()->max('a.date'))->getQuery()->getResult();
    $query->andWhere('a.date = :myDate');
}else{
    $myDate = $date; //Added according to my UDPATE
    $query->andWhere('a.date = :myDate');
}

$query->setParameters(array(
        'productId' => $productId,
        'id' => $id,
        'myDate' => $myDate
    ));

return $query;

UPDATE :

Don't really sure about your $date variable in your condition but maybe add something in your else statement.