Pathik Vejani Pathik Vejani - 9 days ago 6
MySQL Question

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?

Answer

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.