I want create this query with yii2 search model
select * from t1 where (title = 'keyword' or content = 'keyword') AND
(category_id = 10 or term_id = 10 )
But I don't know how to use orFilterWhere
and andFilterWhere
.
My code in search model:
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])
}
//...
}
But it creates this query:
select * from t1 where title = 'keyword' or content = 'keyword' or
category_id = 10 or term_id = 10
First, your required sql statement should be something like this:
select *
from t1
where ((title LIKE '%keyword%') or (content LIKE '%keyword%'))
AND ((category_id = 10) or (term_id = 10))
So your query builder should be something like this:
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]]);
}...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With