'Yii2 add LIKE condition with "%" wildcard on the one side
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\%%'
Solution 1:[1]
You need set the fourth 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 generatename LIKE '%tester'
.
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Stijn de Witt |
Solution 2 | Juan Antonio |