我想用yii2搜索模型
创建此查询select * from t1 where (title = 'keyword' or content = 'keyword') AND
(category_id = 10 or term_id = 10 )
但我不知道如何使用orFilterWhere
和andFilterWhere
。
我在搜索模型中的代码:
public function search($params) {
$query = App::find();
//...
if ($this->keyword) {
$query->orFilterWhere(['like', 'keyword', $this->keyword])
->orFilterWhere(['like', 'content', $this->keyword])
}
if ($this->cat) {
$query->orFilterWhere(['category_id'=> $this->cat])
->orFilterWhere(['term_id'=> $this->cat])
}
//...
}
但它会创建此查询:
select * from t1 where title = 'keyword' or content = 'keyword' or
category_id = 10 or term_id = 10
答案 0 :(得分:47)
首先,您所需的sql语句应该是这样的:
select *
from t1
where ((title LIKE '%keyword%') or (content LIKE '%keyword%'))
AND ((category_id = 10) or (term_id = 10))
所以你的查询构建器应该是这样的:
public function search($params) {
$query = App::find();
...
if ($this->keyword) {
$query->andFilterWhere(['or',
['like','title',$this->keyword],
['like','content',$this->keyword]]);
}
if ($this->cat) {
$query->andFilterWhere(['or',
['category_id'=> $this->cat],
['term_id'=> $this->cat]]);
}...