23

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\%%'
Jonathan DS
  • 2,050
  • 5
  • 25
  • 48
Hossam Aldeen Ahmed
  • 772
  • 1
  • 8
  • 20

2 Answers2

53

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 generate name LIKE '%tester'.

Stijn de Witt
  • 40,192
  • 13
  • 79
  • 80
nadar
  • 1,008
  • 11
  • 15
5

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

Juan Antonio
  • 2,451
  • 3
  • 24
  • 34
killlinuxkill
  • 337
  • 3
  • 8