Answer the question
In order to leave comments, you need to log in
How to organize search by related fields in Yii2?
Good afternoon!
I'm setting up a search in gridview, I ran into a banal problem. In the output table, fields from related tables are not searched. I tried many found examples and guides, did not help. Tell me, please, maybe I missed something out of sight, poke your nose.
Specialist model with User and Organization relationships:
class Specialist extends Specialists
{
/**
* @return \yii\db\ActiveQuery
*/
public function getUser()
{
return $this->hasOne(UserModel::class, ['id' => 'id_user']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getOrganization()
{
return $this->hasOne(Organization::class, ['id' => 'id_organization']);
}
}
class SpecSearch extends Specialist
{
public $userLogin;
public $organizationShortName;
/**
* @return array
*/
public function rules()
{
return [
[['id'], 'integer'],
[['fullname', 'organizationShortName', 'reg_date', 'userLogin'], 'safe'],
];
}
public function scenarios()
{
return Model::scenarios();
}
/**
* @param $params
* @return ActiveDataProvider
*/
public function search($params)
{
$query = Specialist::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$dataProvider->setSort(
[
'attributes' => ['id', 'fullname', 'userLogin']
]);
if (!($this->load($params) && $this->validate())) {
$query->joinWith(['organization', 'user'], true);
return $dataProvider;
}
$query->andFilterWhere(
[
'id' => $this->id,
]);
$query->andFilterWhere(['like', 'fullname', $this->fullname])
->andFilterWhere(['like', 'user.login', $this->userLogin])
->andFilterWhere(['like', 'organization.short_name', $this->organizationShortName])
->andFilterWhere(['like', 'reg_date', $this->reg_date]);
return $dataProvider;
}
}
public function actionIndex()
{
$searchModel = new SpecSearch();
$dataProvider = $searchModel->search(Yii::$app->request->get());
return $this->render('index',
[
'dataProvider' => $dataProvider,
'searchModel' => $searchModel,
]);
}
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' =>
Answer the question
In order to leave comments, you need to log in
Good evening.
In the model
$query = Specialist::find()->with(['organization', 'user']);
$this->load($params);
if (!$this->validate()) {
return $dataProvider;
}
$searchModel = new SpecSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question