【问题标题】:Between in query builder and Symfony2在查询生成器和 Symfony2 之间
【发布时间】:2014-12-17 13:20:25
【问题描述】:

用户进入高级搜索的形式。他可以输入几个值和一些范围滑块价格(jquery ui 小部件)。然后在控制器中,我获取值并希望找到所有行,其中至少有一个条件将被计算。 这是存储库的代码:

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

当起始价格和目标价格等于 271 和 278 时,我得到的价格是 300。我做错了什么?

【问题讨论】:

    标签: php symfony doctrine query-builder


    【解决方案1】:

    我只是快速浏览了一下,但我认为这与您使用orWhere() 的事实有关。不应该是andWhere()吗?

    现在您的查询可能会返回所有结果,其中t.bag = :bagOR 的价格在$startPrice$targetPrice 之间,这解释了您描述的行为。我猜你也会得到价格合适但bag 属性与$bag 参数不匹配的结果。

    编辑:

    由于某些过滤器可能未设置,因此您只想在设置时应用它们。我认为最好的方法是使用 PHP if 语句动态构建查询。例如:

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

    【讨论】:

    • 是的,你是对的,我的错。但是,如果我只想得到 pricesm 和 bag 的结果怎么办?
    • 所以你想要 QueryBuilder 相当于 WHERE price BETWEEN :startPrice AND :targetPrice AND (bag = :bag OR bag IS NULL)?
    • 是的,类似这样,问题是,我将在控制器中获得多个输入(包、价格等),然后我需要找到所有这些至少存在一个的帖子东西...
    • 现在你让我很困惑。也许您可以用您尝试完成的确切行为来更新您的问题?
    • 我会马上做的)
    猜你喜欢
    • 2012-03-18
    • 1970-01-01
    • 2012-10-05
    • 2013-03-23
    • 1970-01-01
    • 2015-07-03
    • 2015-10-08
    • 2016-08-03
    • 1970-01-01
    相关资源
    最近更新 更多