Doctrine中如果参数为null,如何忽略where语句?

问题描述 投票:0回答:1

我在 Doctrine 中的 QueryBuilder 有问题。我编写了一个有 2 个参数的查询,它们影响

where
语句。如果相关参数是
where
,我想忽略
null
语句。例如,如果
$play = 3
$theater = null
,则查询必须返回包含第 3 场戏和任何剧院的所有门票。

这是我当前的代码:

public function getAllSearchedTickets($play,$teater){
    return $this->getEntityManager()->createQuery('
        select s from mtadminBundle:ReserveLocation s
        join s.reserve a
        join a.sance b
        where a.acceptCode != 0
        and b.play = :play 
        and b.teater = :teater')
        ->setParameters(array('play'=>$play,'teater'=>$teater))->getResult();
}

谢谢你。

sql symfony doctrine
1个回答
5
投票

您应该为此使用 QueryBuilder,为了更有效地完成此操作,我将向您展示如何操作,然后以 QueryBuilder 为例:

你的:

public function getAllSearchedTickets($play,$teater){
    $query = 'select s from mtadminBundle:ReserveLocation s'.
        'join s.reserve a'.
        'join a.sance b'.
        'where a.acceptCode != 0');

    $paramArray = array();
    if( $play ) {
        $query .= ' and b.play = :play';
        $paramArray['play'] = $play;
    }
    if( $teater ) {
        $query .= ' and b.teater = :teater';
        $paramArray['teater '] = $teater;
    }

    return $this->getEntityManager()->createQuery($query)
        ->setParameters($paramArray)->getResult();
}

查询生成器:

public function getAllSearchedTickets($play,$teater){
    $queryBuilder = $this->getEntityManager()->createQueryBuilder();
    $queryBuilder->select('s')
        ->from('mtadminBundle:ReserveLocation', 's')
        ->join('s.reserve', 'a')
        ->join('a.sance', 'b')
        ->where('a.acceptCode != 0');

    if( $play ) {
        $queryBuilder->andWhere('b.play = :play');
        $queryBuilder->setParameter('play', $play);
    }
    if( $teater ) {
        $queryBuilder->andWhere('b.teater = :teater');
        $queryBuilder->setParameter('teater', $teater);
    }

    return $queryBuilder->getResult();
}
© www.soinside.com 2019 - 2024. All rights reserved.