Configuring the search in gridview, faced with a banal problem. In the displayed table, no search is added to the fields from the related tables. I tried many examples found and guides, did not help.

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']); } } 

Model Search:

 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; } } 

Controller:

 public function actionIndex() { $searchModel = new SpecSearch(); $dataProvider = $searchModel->search(Yii::$app->request->get()); return $this->render('index', [ 'dataProvider' => $dataProvider, 'searchModel' => $searchModel, ]); } 

View:

 <?= GridView::widget([ 'dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'columns' => 
  • I would also look at the speakers in the gridview. - fedornabilkin

2 answers 2

I figured it out myself, it was enough to do this in the column description:

 'label' => 'Организация', 'attribute' => 'short_name', 'value' => 'organization.short_name', 

    In order to search through the fields of a related table, you must attach this table to the main one. This is done using $query->joinWith(['organization', 'user'], true); , but in this case the join only happens if it failed to load data into the model or did not pass validation. It will be correct to add this construction before the second return.