我想用yii2框架添加过滤条件,这个条件必须生成以下请求:
select count(*) from v_ressource
where
(
(
str_to_date('27/04/2016', '%d/%m/%Y')
between str_to_date(erDateDebut, '%d/%m/%Y')
and str_to_date(erDateFin, '%d/%m/%Y')
)
and erDateFin is not null
)
or
(
(
str_to_date('27/04/2016', '%d/%m/%Y')
between str_to_date(erDateDebut, '%d/%m/%Y')
and now()
)
and erDateFin is null
);
正如您所看到的,'或'条件中存在'和'条件。
我在ModelSearch中有以下代码:
$query
->andFilterWhere([
'between',
'str_to_date(\'' . $this->dateRecherche . '\', \'%d/%m/%Y %H:%i\')',
new Expression('str_to_date(erDateDebut, \'%d/%m/%Y %H:%i\')'),
new Expression('str_to_date(erDateFin, \'%d/%m/%Y %H:%i\')'),
])
->andFilterWhere([
'not', ['erDateFin' => null],
]);
$query
->orFilterWhere([
'between',
'str_to_date(\'' . $this->dateRecherche . '\', \'%d/%m/%Y %H:%i\')',
new Expression('str_to_date(erDateDebut, \'%d/%m/%Y %H:%i\')'),
new Expression('now()'),
])
->andFilterWhere([
'is', 'erDateFin', null,
]);
两者都为null且不为null条件不会出现在生成的请求中,并且没有“嵌套”条件(以及条件中的条件)
感谢您的帮助
答案 0 :(得分:1)
andFilterWhere
和orFilterWhere
不允许以这种方式嵌套,因为它们对查询对象进行操作 - 而不是对条件对象进行操作。您可以这样定义查询:
$query->where(
['and',
[
'between',
'str_to_date(\'' . $this->dateRecherche . '\', \'%d/%m/%Y %H:%i\')',
new Expression('str_to_date(erDateDebut, \'%d/%m/%Y %H:%i\')'),
new Expression('str_to_date(erDateFin, \'%d/%m/%Y %H:%i\')'),
],
[
'not', ['erDateFin' => null],
]
]);
$query->orWhere(
['and',
[
'between',
'str_to_date(\'' . $this->dateRecherche . '\', \'%d/%m/%Y %H:%i\')',
new Expression('str_to_date(erDateDebut, \'%d/%m/%Y %H:%i\')'),
new Expression('now()'),
],
[
'is', 'erDateFin', null,
]
]);
您甚至可以将其全部放入一个where
方法调用中:
$query->where(
['or',
['and',
[
'between',
'str_to_date(\'' . $this->dateRecherche . '\', \'%d/%m/%Y %H:%i\')',
new Expression('str_to_date(erDateDebut, \'%d/%m/%Y %H:%i\')'),
new Expression('str_to_date(erDateFin, \'%d/%m/%Y %H:%i\')'),
],
[
'not', ['erDateFin' => null],
]
],
['and',
[
'between',
'str_to_date(\'' . $this->dateRecherche . '\', \'%d/%m/%Y %H:%i\')',
new Expression('str_to_date(erDateDebut, \'%d/%m/%Y %H:%i\')'),
new Expression('now()'),
],
[
'is', 'erDateFin', null,
]
]
]);
我使用了where方法,而不是filterWhere方法,因为您可能不希望从查询中删除empty operands。有关过滤的更多信息,请参见here。 where还会记录和以及或运算符。
您可能已经知道,可以使用
完成计数$count = $query->count();