Doctrine 2 dynamic query

I am trying to do a dynamic doctrine search query. And it does not work

$em = $this->getDoctrine()->getEntityManager(); $city = 'new york'; $minprice = 500; $maxprice = 1000; $testquery = "SELECT p FROM AcmeTestBundle:Car p WHERE p.city = :city"; $testparam = array('city' => $city,); if ($minprice != '') { if ($maxprice != '') { $testquery .= " and p.price BETWEEN :minprice AND :maxprice"; $testparam .= array( 'minprice' => $minprice, 'maxprice' => $maxprice, ); } } $testquery .= " ORDER BY p.price ASC"; $query = $em->createQuery($testquery)->setParameters($testparam); $result = $query->getResult(); 

Is there a better way to do this?

+4
source share
2 answers

Basically, the approach you took is fine. However, I see at least two things wrong.

1) Doctrine does not support BETWEEN, so you will need something like:

  $testquery .= " and p.price >= :minprice AND p.price <= :maxprice"; 

2) .. = - only a string operator, you cannot use it with arrays. This way, you will need to do something like this (you can do array_merge, but this seems like overkill):

  $testParam['minPrice'] = $minPrice; $testParam['maxPrice'] = $maxPrice; 
+2
source

In php you cannot use .= With arrays. Instead do

 $testparam['minprice'] = $minprice; $testparam['maxprice'] = $maxprice; 
0
source

Source: https://habr.com/ru/post/1447792/


All Articles