简体   繁体   中英

Conditionally adding to Doctrine WHERE clause

How should one conditionally add constraints to the WHERE clause? For instance, if sex , maxAge , and minAge is provided, the WHERE clause should be WHERE sex=? AND maxAge<? AND minAge>? WHERE sex=? AND maxAge<? AND minAge>? , but if maxAge is not provided, it should be WHERE sex=? AND minAge>? WHERE sex=? AND minAge>? The logic below might work to determine whether where() or andWhere() is used, however, surely shouldn't be used.

<?php
// $qb instanceof QueryBuilder

$qb->select('u')
->from('User', 'u');

if(isset($param['sex'])) {
    $qb->where('u.sex = ?1')->setParameter(1, $param['sex']);
}

if(isset($param['maxAge'])) {
    if(isset($param['sex'])) {
        $qb->andWhere('u.age < ?2')->setParameter(2, $param['maxAge']);
    }
    else {
        $qb->where('u.age < ?2')->setParameter(2, $param['maxAge']);
    }
}

if(isset($param['minAge'])) {
    if(isset($param['sex'])|| isset($param['maxAge'])) {
        $qb->andWhere('u.age > ?3')->setParameter(3, $param['minAge']);
    }
    else {
        $qb->where('u.age > ?3')->setParameter(3, $param['minAge']);
    }
}

There's no need for all those conditional checks. Just use andWhere everywhere.

<?php
// $qb instanceof QueryBuilder

$qb->select('u')
    ->from('User', 'u');

if(isset($param['sex'])) {
    $qb->andWhere('u.sex = :sex')->setParameter('sex', $param['sex']);
}

if(isset($param['maxAge'])) {
    $qb->andWhere('u.age < :maxAge')->setParameter('maxAge', $param['maxAge']);
}

if(isset($param['minAge'])) {
    $qb->andWhere('u.age > :minAge')->setParameter('minAge', $param['minAge']);
}

I suppose you can create a single string for where :

$whereArr = $whereParams = [];
foreach (['sex' => 'u.sex = :sex', 'maxAge' => 'u.age < :maxAge', 'minAge' => 'u.age > :minAge'] as $key => $clause) {
    if (isset($params[$key])) {
        $whereArr[] = $clause;
        $whereParams[':' . $key] = $params[$key];
    }
}

if ($whereArr) {
    $qb->where(implode(' and ', $whereArr))->setParameters($whereParams);
}

I'll probably go with ehymel's answer, but the following should work.

<?php
// $qb instanceof QueryBuilder

$qb->select('u')
->from('User', 'u');

$where = [];

if(isset($param['sex'])) {
    $where[] = $qb->expr()->eq('sex', ':sex');
}

if(isset($param['maxAge'])) {
    $where[] = $qb->expr()->lte('maxAge', ':maxAge');
}

if(isset($param['minAge'])) {
    $where[] = $qb->expr()->gte('minAge', ':minAge');
}

if($where) {
    $params=array_intersect_key($params, array_flip('sex','minAge','maxAge'));
    $qb->add('where', $qb->expr()->andX(...$where))->setParameters($params);;
}

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