我有一个User表,它与auth_assignment表连接以获取用户角色并将其显示在用户的gridview中。角色属性显示在gridview上,但是当我单击操作按钮编辑时,表单已加载且角色属性为空。
我试图能够直接在用户更新操作中更新联接表中的字段。有可能吗?
我的模特:
class User extends ActiveRecord implements \yii\web\IdentityInterface
{
public $perfil;
public function attributeLabels()
{
return [
'permissions' => 'Permissões',
'first_name' => 'Primeiro Nome',
'last_name' => 'Último Nome',
'perfil' => 'Role',
];
}
我的index.php
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
// ['class' => 'yii\grid\SerialColumn'],
'id',
'first_name',
'last_name',
'username',
[
'attribute'=>'perfil',
'value'=>'authAssignment.item_name'
],
我的_form.php:
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'id')->textInput() ?>
<?= $form->field($model, 'first_name')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'last_name')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'username')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'perfil')->textInput(['maxlength' => true]) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
我加入用户模型并在搜索模型中访问它:
public function getAuthAssignment() {
return $this->hasOne(AuthAssignment::className(), ['user_id' => 'id']);
}
if (Yii::$app->controller->id == 'user' && Yii::$app->controller->action->id == 'index') {
$query->joinWith('authAssignment');
}
我希望能够在单击操作列编辑按钮时更新角色属性以及其他字段。 我能够在gridview中显示角色(perfil)列,但是当我点击更新按钮时,该字段变为空。
如何更新来自联接表的字段?
答案 0 :(得分:0)
为了更新联接表字段,我在更新函数中实例化了auth_assignment表,并且当单击保存按钮时,我将发布的值分配给item_name字段。这是我的更新功能:
public function actionUpdate($id)
{
$model = $this->findModel($id);
// display joined table field in the update form
$model->perfil = $model->authAssignment['item_name'];
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
// get the auth_assignment table
$authAssig = AuthAssignment::find()->where(['user_id' => $id])->one();
// update field using postedform value
$authAssig->item_name = Yii::$app->request->post()['User']['perfil'];
if ($model->save() && $authAssig->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
} else {
return $this->render('update', [
'model' => $model,
]);
}
}