簡體   English   中英

在查詢生成器和Symfony2之間

[英]Between in query builder and Symfony2

用戶采用高級搜索的形式。 他可以輸入一些值,以及一些范圍滑塊價格(jquery ui小部件)。 然后在Controller中我獲取值並想要查找所有行,其中至少有一個條件將被計算。 這是存儲庫的代碼:

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的帖子。我做錯了什么?

我剛剛給出了這個快速查看,但我認為這與您使用orWhere()的事實有關。 不應該是和andWhere()

現在你的查詢可能會返回所有結果,其中t.bag = :bag OR ,其中價格在$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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM