/** * 用户角色关系 * @return [type] [description] */ public function getRole() { return $this->hasOne(AuthAssignment::className(), ['user_id' => 'service_id']); }
/** * Updates an existing Service model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id * @return mixed */ public function actionUserUpdate($id) { $model = $this->findModel($id); $model->setScenario('update'); if (Yii::$app->request->getIsPost()) { $params = Yii::$app->request->post(); //密码为空就不保存 if (empty($params['Service']['service_password'])) { unset($params['Service']['service_password']); } else { $params['Service']['service_password'] = Yii::$app->getSecurity()->generatePasswordHash($params['Service']['service_password']); } if ($model->load($params) && $model->save()) { $role = AuthAssignment::findOne(['user_id' => $model->service_id]); //$role没有查到时插入一条记录 if (!$role) { $auth = Yii::$app->authManager; $authorRole = $auth->getRole($params['Service']['roles']); $auth->assign($authorRole, $model->service_id); } else { $role->item_name = $params['Service']['roles']; $role->save(true, ['item_name']); } } Yii::$app->session->setFlash('success', '用户修改成功'); return $this->redirect(['user-view', 'id' => $model->service_id]); } $auth = Yii::$app->authManager->getAssignments($model->service_id = 60); $model->roles = isset(array_keys($auth)[0]) ? array_keys($auth)[0] : AuthItem::DEFAULT_ROLE; return $this->render('user-update', ['model' => $model, 'roles' => ArrayHelper::map(Yii::$app->authManager->getRoles(), 'name', 'name')]); }
/** * @return \yii\db\ActiveQuery */ public function getAuthAssignments() { return $this->hasMany(AuthAssignment::className(), ['item_name' => 'name']); }