Answer the question
In order to leave comments, you need to log in
What is the correct way to do search filter and sort in Yii2 GridView with two fields from the same table?
Good afternoon,
I made a filter on the associated model, guided by these articles:
webdishes.ru/filter
https://nix-tips.ru/yii2-sortirovka-i-filtr-gridvi...
The fact is that my main model is - Orders refers to the Places model with 2 foreign keys - place_from_id , place_to_id .
The following code example handles filtering for placeFrom :
class OrdersSearch extends Orders
{
public $placeFromName;
public $placeToName;
...
public function rules()
{
return [
...
[['placeFromName','placeToName'], 'safe']
....
];
}
....
public function search($params)
{
$query = Orders::find();
$query->joinWith(['placeFrom']); // , 'placeTo
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$dataProvider->sort->attributes['placeFrom'] = [
'asc' => ['t_places.name' => SORT_ASC],
'desc' => ['t_places.name' => SORT_DESC],
];
$dataProvider->sort->attributes['placeTo'] = [
'asc' => ['t_places.name' => SORT_ASC],
'desc' => ['t_places.name' => SORT_DESC],
];
if (!($this->load($params) && $this->validate())) {
return $dataProvider;
}
$query->andFilterWhere([
'place_from_id' => $this->place_from_id,
'place_to_id' => $this->place_to_id,
....
]);
$query
->andFilterWhere(['like', 'LOWER(t_places.name)', strtolower($this->placeFromName)])
->andFilterWhere(['like', 'LOWER(t_places.name)', strtolower($this->placeToName)])
;
return $dataProvider;
}
...
}
$query->joinWith(['placeFrom']); // , 'placeTo
$query->joinWith(['placeFrom' , 'placeTo]);
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question