[英]Conditionally adding to Doctrine WHERE clause
How should one conditionally add constraints to the WHERE clause? 应该如何有条件地向WHERE子句添加约束? For instance, if sex
, maxAge
, and minAge
is provided, the WHERE clause should be WHERE sex=? AND maxAge<? AND minAge>?
例如,如果提供了sex
, maxAge
和minAge
,则WHERE子句应为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>?
,但如果未提供maxAge
,则应为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. 下面的逻辑可能会确定使用where()
或andWhere()
,但是,肯定不应该使用。
<?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. 只需在任何地方使用andWhere
。
<?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
: 我想您可以为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. 我可能会同意ehymel的回答,但是以下方法应该可行。
<?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);;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.