Pathik Vejani Pathik Vejani - 3 months ago 35
MySQL Question

Select data with like operator in yii2

How can i retrieve data with


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 != ''**
->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?


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.