2 years ago
#70152
yolenoyer
Set a field value based on an expression in DQL
I'm trying to update a field in all the lines of a database table, by using an expression as the value. In practice, the field is_new_arrival
must be set to true
only if new_arrival_start_date
and new_arrival_end_date
are not null and the current day is included into these two dates.
Here is a working native Postgre request of the expected behaviour:
UPDATE product p SET is_new_arrival =
p.new_arrival_start_date IS NOT NULL
AND p.new_arrival_end_date IS NOT NULL
AND NOW() BETWEEN p.new_arrival_start_date AND p.new_arrival_end_date;
Now I would like to use DQL and/or Doctrine QueryBuilder instead of using native Sql, so I tried this:
$qb = $entityManager->createQueryBuilder();
$expr = $qb->expr();
$query = $qb
->update(Product::class, 'p')
->set(
'p.newArrival',
$expr->andX(
$expr->isNotNull('p.newArrivalStartDate'),
$expr->isNotNull('p.newArrivalEndDate'),
$expr->between('CURRENT_TIMESTAMP()', 'p.newArrivalStartDate', 'p.newArrivalEndDate')
)
)
->getQuery();
$query->execute();
But it gives me this error:
In QueryException.php line 54:
[Syntax Error] line 0, col 90: Error: Expected end of string, got 'IS'
In QueryException.php line 43:
UPDATE App\Bundle\ProductBundle\Entity\Product p SET p.newArrival = p.newArrivalStartDate IS NOT NULL AND p.newArrivalEndDate IS NOT NULL AND (CURRENT_TIMESTAMP()
BETWEEN p.newArrivalStartDate AND p.newArrivalEndDate)
It seems that DQL does not handle expressions for UPDATE ... SET ...
statements. How can I solve this problem and use the QueryBuilder (or DQL directly) to perform this query?
php
doctrine
dql
0 Answers
Your Answer