dongxun6690 2016-03-27 17:29
浏览 117
已采纳

如果提供条件,则Doctrine为createQueryBuilder添加条件

I have following function:

public function latestNews($tags = array(), $categories = array(), $authors = array(), $lang = 'en', $source = '', $limit = 20) {
    return $this->createQueryBuilder('News')
    ->field('tags')->in($tags)
    ->field('categories')->in($category)
    ->field('authors')->in($authors)
    ->field('lang')->equals($lang)
    ->sort('date' -> 'DESC')
    ->field('source')->equals($source)
    ->limit($limit)
    ->getQuery()
    ->execute();
}

I want if variables such as $tags, $categories, $authors or $source provided by function caller this variables affect on the createQueryBuilder, but if each of them does not provide by the function caller(variable with default value) they don't affect createQueryBuilder and make this condition neutral on query. One way is I make the query with many if condition but it is very messy. Is there any better solution?

  • 写回答

2条回答 默认 最新

  • doubao6464 2016-03-27 17:51
    关注

    Something like this should do the trick:

    public function latestNews($tags = array(), $categories = array(), authors = array(), $lang = 'en', $source = '', $limit = 20) {
        $inClauses = ['tags', 'categories', 'authors'];
        $equalClauses = ['lang', 'source'];
        $qb = $this->createQueryBuilder('News');
    
        foreach ($inClauses as $field) {
            $realVar = ${$field};
    
            if (!empty($realVar)) {
                $qb->field($field)->in($realVar);
            }
        }
    
        foreach ($equalClauses as $field) {
            $realVar = ${$field};
    
            if ($realVar) {
                $qb->field($field)->equals($realVar);
            }
        }
    
        return $qb
            ->sort('date' -> 'DESC')
            ->limit($limit)
            ->getQuery()
            ->execute();
    }
    

    A bit ugly, but I don't see any better alternative.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?