YII2的SearchModel高级用法-关联查询



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'],
                            ],


鼎云博客
  • 最新评论
  • 总共0条评论