简体   繁体   中英

Between in query builder and Symfony2

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM