如何将输入数据插入特定列。
例如,我在表 Clinic 中有列 ClinicName 和 ClinicArea。我制作了一个仅用于插入和保存 ClinicName 的表格(model2)。当我尝试注册表格时,它将信息保存到表人(模型)中,但模型2不保存到表诊所。但是当我包含 model2 ClinicArea 表单时,数据可以保存。我只想插入诊所名称。下面是代码:
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(); ?>
控制器.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',
];
}
在诊所模型中检查您设置的规则: ['clinicName', 'clinicArea', 'personId'] 为必填项,不通过则无法保存模型,参见文档yii2验证规则:
requiredValue: the desired value that the input should be. If not set, it means the input should not be empty.
您将有两种方式:
您说过 ClinicArea id 对您来说并不重要,因此将其从所需规则中删除。
提示:如果设置为Not Null,请检查数据库,如果尝试使用clinicArea = null保存模型,则会出错
您已根据需要设置了 ['clinicName', 'clinicArea', 'personId'],因此当模型尝试保存数据时,会执行此验证,并且模型无法设置数据。
如果你想强制保存数据那么你需要这样写:
$model2->保存(假);
但这不是正确的方法。
第二种方法是根据需要和使用为单个字段集创建场景。