Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 how can I use a like query for first character only

Tags:

php

mysql

yii2

How can I use a like query and limit to the first character only for example my code below works however it does it for all characters for example if an item was called end it would appear in e, n & d rather than just e the starting character/letter.

Current Query/Code

    public function actionAlphabet($id)
{
    $this->layout = 'directory';

    $query = Directory::find()
    ->where(['LIKE', 'name', $id]);

    $dataProvider = new ActiveDataProvider([
        'query' => $query
    ]);

    return $this->render('index', [
        'dataProvider' => $dataProvider,
    ]);
} 
like image 454
con322 Avatar asked Mar 07 '15 09:03

con322


1 Answers

You should simply try :

$query = Directory::find()
    ->where(['LIKE', 'name', $id.'%', false]);

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'.

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

EDIT: my mistake, updated thanks to Latikov Dmitry comment.

like image 196
soju Avatar answered Sep 27 '22 17:09

soju