Reputation: 4501
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
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
Reputation: 133380
Try something like this :
$query = Post::find();
$query->andFilterWhere(['like', 'title', $searchVal])
->orderBy(['added_date_time' => SORT_DESC])
->all();
Upvotes: 18
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