Skip to content

Instantly share code, notes, and snippets.

@proditis
Created November 2, 2019 10:26
Show Gist options
  • Save proditis/99808a892d5c945c18fb18ff4c3b7fd9 to your computer and use it in GitHub Desktop.
Save proditis/99808a892d5c945c18fb18ff4c3b7fd9 to your computer and use it in GitHub Desktop.
Customizing Yii2 ModelSearch.php to search FK and other related models. The following example of `SpinQueue` search on a junction model, searches for the name of `target` and `player` on the related tables.
<?php
class ModelSearch extends SpinQueue
{
public $target;
public $player;
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['target_id', 'player_id'], 'integer'],
[['created_at','target','player'], 'safe'],
];
}
/**
* {@inheritdoc}
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
$query = SpinQueue::find()->joinWith(['target','player']);
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'target_id' => $this->target_id,
'player_id' => $this->player_id,
'created_at' => $this->created_at,
]);
$query->andFilterWhere(['like', 'player.id', $this->player]);
$query->orFilterWhere(['like', 'player.username', $this->player]);
$dataProvider->setSort([
'attributes' => array_merge(
$dataProvider->getSort()->attributes,
[
'player' => [
'asc' => [ 'player_id' => SORT_ASC],
'desc' => ['player_id' => SORT_DESC],
],
]
),
]);
$query->andFilterWhere(['like', 'target.id', $this->target]);
$query->orFilterWhere(['like', 'target.fqdn', $this->target]);
$dataProvider->setSort([
'attributes' => array_merge(
$dataProvider->getSort()->attributes,
[
'target' => [
'asc' => [ 'target_id' => SORT_ASC],
'desc' => ['target_id' => SORT_DESC],
],
]
),
]);
return $dataProvider;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment