如何将输入数据插入特定列。
例如,我在表clinic中有列clinicName和clinicArea。我创建了一个表单,只用于插入和保存clinicName(model2)。当我尝试注册表格时,它将信息保存到表person for(模型)中,但模型2未保存到表clinic中。但是当我包含model2 clinicArea表单时,数据可以保存。我只想插入clinicName。下面是代码:
form.php
<div class="person-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'personName')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'personNumber')->textInput() ?>
<?= $form->field($model2, 'clinicName')->textInput(['maxlength' => true]) ?>
<div class="form-group">
<?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
controller.php
public function actionCreate()
{
$model = new Person();
$model2 = new Clinic();
if ($this->request->isPost) {
if ($model->load($this->request->post()) && $model2->load($this->request->post())) {
$model->save();
$model2->personId = $model->personId;
$model2->save();
return $this->redirect(['view', 'personId' => $model->personId]);
}
} else {
$model->loadDefaultValues();
}
return $this->render('create', [
'model' => $model,
'model2' => $model2,
]);
}
临床模型
public static function tableName()
{
return 'clinic';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['clinicName', 'clinicArea', 'personId'], 'required'],
[['personId'], 'integer'],
[['clinicName', 'clinicArea'], 'string', 'max' => 255],
[['personId'], 'exist', 'skipOnError' => true, 'targetClass' => Person::class, 'targetAttribute' => ['personId' => 'personId']],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'cliniId' => 'Clini ID',
'clinicName' => 'Clinic Name',
'clinicArea' => 'Clinic Area',
'personId' => 'Person ID',
];
}
1条答案
按热度按时间qvtsj1bj1#
根据您提供的代码,问题在于“clinicArea”列在Clinic模型的“rules”方法中被标记为必需的。
要只插入“clinicName”而不插入“clinicArea”,需要修改Clinic模型中的“rules”方法,使“clinicArea”属性可选。以下是诊所模型规则的更新版本: