Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 add LIKE condition with "%" wildcard on the one side

Tags:

mysql

yii2

I want to add like condition with % wildcard on the one side, like:

where name like 'value%'

My code:

Table::find()->filterWhere(['like', 'name' , $_GET['q'].'%' ])
        ->all();

But query result is:

 where name like '%value\%%'
like image 632
Hossam Aldeen Ahmed Avatar asked Sep 03 '16 07:09

Hossam Aldeen Ahmed


2 Answers

You need set the third operand to false in order to use custom where like conditions:

Table::find()->where(['like', 'name', $_GET['q'] . '%', false]);

From the docs:

Sometimes, you may want to add the percentage characters to the matching value by yourself, you may supply a third operand false to do so. For example, ['like', 'name', '%tester', false] will generate name LIKE '%tester'.

like image 172
nadar Avatar answered Oct 22 '22 19:10

nadar


You can use:

Table::find()->where(new \yii\db\Expression('name LIKE :term', [':term' => $_GET['q'] . '%']));

or

Table::find()->where(['like', 'name', $_GET['q'] . '%', false]);

or

$likeCondition = new \yii\db\conditions\LikeCondition('name', 'LIKE', $_GET['q'] . '%');
$likeCondition->setEscapingReplacements(false);
Table::find()->where($likeCondition);

More info at https://www.yiiframework.com/doc/api/2.0/yii-db-conditions-likecondition

like image 33
killlinuxkill Avatar answered Oct 22 '22 17:10

killlinuxkill