Reputation: 2567
User go te the form of advanced search. He can input few values, and some range slider price(jquery ui widget). Then in Controller I get values and want find all rows, where at least one condition will mathced. Here is code of repository:
public function advancedSearch($bag, $startPrice, $targetPrice)
{
$parameters = ['bag' => $bag];
$query = $result = $this->getEntityManager()
->createQueryBuilder()
->select('t')
->from('VputiTripBundle:Trip', 't');
$query->orWhere('t.bag = :bag');
$query->orWhere(
$query->expr()->between('t.price', $startPrice, $targetPrice)
);
$result = $query
->setParameters($parameters)
->setMaxResults(1)
->getQuery()
->getResult();
return $result;
}
Whe start- and target- price equal to 271 and 278, I get post where price 300. What I am doing wrong ?
Upvotes: 1
Views: 1162
Reputation: 11423
I've just given this a quick look but I think it has to do with the fact that you're using orWhere()
. Shouldn't it be andWhere()
?
Right now your query is probably returning all results where t.bag = :bag
OR
where the price is between $startPrice
and $targetPrice
, which explains the behavior you described. I'm guessing you also get results where the price is right but where the bag
property doesn't match the $bag
parameter.
Edit:
Since some of the filters might not be set, you only want to apply them when they are. I think the best way to go here is to build your query dynamically by using PHP if
statements. For example:
public function advancedSearch($bag, $startPrice, $targetPrice)
{
$parameters = array();
// $query = $result = $this->getEntityManager() ... etc
if (!empty($bag)) {
$query->andWhere('t.bag = :bag');
$parameters['bag'] = $bag;
}
if (!empty($startPrice) && !empty($targetPrice)) {
$query->andWhere(
$query->expr()->between('t.price', $startPrice, $targetPrice)
);
}
// $result = $query->setParameters($parameters) ... etc
return $result;
}
Upvotes: 3