This code makes an SQL query. The last andWhere()
method adds a LIKE
condition with one percentage sign at the right side of the string.
I'm wondering if there is a better way to do it.
public function prepareDataProvider()
{
/* @var $modelClass \yii\db\ActiveRecord */
$modelClass = $this->modelClass;
$query = $modelClass::find()
->where('published=1')
->select([
'id',
'city_id',
'city_district_id',
'seller_net_id',
'name',
'address',
'type',
]);
// filters
if ($city_id = \Yii::$app->request->getQueryParam('city_id'))
$query->andWhere('city_id = :city_id',[':city_id'=>$city_id]);
if ($city_district_id = \Yii::$app->request->getQueryParam('city_district_id'))
$query->andWhere('city_district_id = :city_district_id',[':city_district_id'=>$city_district_id]);
$city_name = \Yii::$app->request->getQueryParam('name');
if ($city_name && mb_strlen($city_name) >= \Yii::$app->params['minSearchChars'])
$query->andWhere(['LIKE' ,'name',strtr($city_name,['%'=>'\%', '_'=>'\_', '\\'=>'\\\\']).'%', false]);
return new ActiveDataProvider([
'query' => $query
]);
}