YII2的SearchModel高级用法-关联查询,跨多个表实现关联查询
基于rageframe2,参考方法:https://getyii.com/topic/364
控制器部分:
/** * @var ModuleDeviceVariableWriteLog */ public $modelClass = ModuleDeviceVariableWriteLog::class; /** * @return string * @throws \yii\web\NotFoundHttpException * @throws \yii\web\UnauthorizedHttpException */ public function actionIndex() { $org_ids = Yii::$app->iotService->moduleOrganization ->getChildIds(Yii::$app->user->identity->org_id, true); $searchModel = new SearchModel( [ 'model' => $this->modelClass, 'scenario' => 'default', // 关联查询条件 'relations' => ['moduleDeviceVariable' => ['title'], 'moduleDeviceVariable.moduleDevice' => ['title']], // 模糊查询 'partialMatchAttributes' => ['id', 'moduleDeviceVariable.title', 'moduleDeviceVariable.moduleDevice.title'], 'defaultOrder' => [ 'id' => SORT_DESC, ], 'pageSize' => $this->pageSize, ] ); $dataProvider = $searchModel ->search(Yii::$app->request->queryParams); $dataProvider->query ->andFilterWhere(['in', $this->modelClass::tableName().'.org_id', $org_ids]) ->andWhere(['>=', $this->modelClass::tableName().'.status', StatusEnum::DISABLED]); return $this->render( $this->action->id, [ 'dataProvider' => $dataProvider, 'searchModel' => $searchModel, ] ); }
GridView 片段:
[ 'attribute' => '设备名称', 'filter' => Html::activeTextInput($searchModel, 'moduleDeviceVariable.moduleDevice.title', ['class' => 'form-control']), 'value' => function ($model) { return $model->moduleDeviceVariable->moduleDevice->title; }, 'format' => 'raw', 'headerOptions' => ['class' => 'col-md-2'], ], [ 'attribute' => '变量名称', 'filter' => Html::activeTextInput($searchModel, 'moduleDeviceVariable.title', ['class' => 'form-control']), 'value' => function ($model) { return $model->moduleDeviceVariable->title; }, 'format' => 'raw', 'headerOptions' => ['class' => 'col-md-2'], ],
无论从事什么行业,只要做好两件事就够了,一个是你的专业、一个是你的人品,专业决定了你的存在,人品决定了你的人脉,剩下的就是坚持,用善良專業和真诚赢取更多的信任。