Pathik Vejani
Pathik Vejani

Reputation: 4501

Select data with like operator in yii2

How can i retrieve data with Like operator?
I have tried this but getting an error:

    use yii\db\Query;
    public function getExportData($searchVal = '')
    {
         $query = new Query;
         if($searchVal != '') { **here i am getting error when searchVall != ''**   
             $query->select('*')->from('post')
             ->where(['like', 'title', $searchVal])
             ->orderBy(['added_date_time' => SORT_DESC]);
             $posts = $query->createCommand()->queryAll();
         } else {
             $query->select('*')->from('post')->orderBy(['added_date_time' => SORT_DESC]);
             $posts = $query->createCommand()->queryAll();
         }
         return $posts;
     }

Is there any simple way for select statement?

Upvotes: 3

Views: 14399

Answers (4)

Kalyan Halder
Kalyan Halder

Reputation: 1585

Best practice is like this:

$query = "SELECT * FROM ".YourModel::tableName()." where title LIKE :param";
$result = YourModel::findBySql($query, [':param' => $param.'%'])->all();

Hope this will help someone.

Upvotes: 1

ScaisEdge
ScaisEdge

Reputation: 133380

Try something like this :

    $query = Post::find();
    $query->andFilterWhere(['like', 'title', $searchVal])
         ->orderBy(['added_date_time' => SORT_DESC])
         ->all();

Upvotes: 18

Insane Skull
Insane Skull

Reputation: 9368

If you want to pass the query using variable then use findBySql() method. For example,

$query = "SELECT * FROM `post` where `title` LIKE 'foo%' ";
$result = Model::findBySql($query)->all();

Hope this will help to solve your problem.

Upvotes: 3

Related Questions