Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

yii2 ActiveQuery 'OR LIKE' filter

Tags:

i have a task - add to search model searching by full name. Full name is first name + last name. So i need to build query like

WHERE first_name LIKE '%var%' OR last_name LIKE '%var%' 

The only way i could do it :

$query->andFilterWhere([ 'OR', 'profiles.first_name LIKE "%' . $this->userFullName . '%" ', 'profiles.last_name LIKE "%' . $this->userFullName . '%"' ]); 

But i dont like it because % its unsafe. I dont know how... I think there is the way to build such query with yii2 active builder, and i would like to get in result smth like

$query->andFilterWhere(['LIKE', 'profiles.first_name', $this->userFullName]); $query->andFilterWhere(['OR LIKE', 'profiles.last_name', $this->userFullName]); 

The problem is in the query Like, i could use array as the values that attribute will be comapred but i cant use array as list of attributes to be compared with.

or

$subQuery1 = Profile::find()->Where(['LIKE', 'profiles.first_name', $this->userFullName]); $subQuery2 = Profile::find()->Where(['LIKE', 'profiles.last_name', $this->userFullName]); //i think its overloaded(3 queries insteadof 1 but still) and the final query $query->andFilterWhere([ 'OR', $subQuery1, $subQuery2 ]); 

Any ideas how to build query whithout "%"?

like image 665
Colohanin Nik Avatar asked Feb 18 '15 20:02

Colohanin Nik


People also ask

How to use query in Yii2?

Also you need to execute the query. $query = (new \yii\db\Query())->select(['title'])->from('topics')->where(['id' => [1, 2, 3]]); $command = $query->createCommand(); $data = $command->queryAll(); $titles = ''; foreach($data as $row) { $titles . = $row['title'] . ', '; } return rtrim($titles, ', ');

What is active query in yii?

An ActiveQuery can be a normal query or be used in a relational context. ActiveQuery instances are usually created by yii\db\ActiveRecord::find() and yii\db\ActiveRecord::findBySql(). Relational queries are created by yii\db\ActiveRecord::hasOne() and yii\db\ActiveRecord::hasMany().

What is active record in Yii2?

Active Record automatically maintains the list of dirty attributes. It does so by maintaining an older version of the attribute values and comparing them with the latest one. You can call yii\db\ActiveRecord::getDirtyAttributes() to get the attributes that are currently dirty.


1 Answers

You should simply try :

$query->andFilterWhere([     'or',     ['like', 'profiles.first_name', $this->userFullName],     ['like', 'profiles.last_name', $this->userFullName], ]); 

or: similar to the and operator except that the operands are concatenated using OR. For example, ['or', ['type' => [7, 8, 9]], ['id' => [1, 2, 3]] will generate (type IN (7, 8, 9) OR (id IN (1, 2, 3))).

Read more : http://www.yiiframework.com/doc-2.0/yii-db-queryinterface.html#where()-detail

like image 186
soju Avatar answered Sep 22 '22 18:09

soju