我目前正在开发一个 Yii2 项目,其中有一个表示表的类,该类包含一个与任何表列不直接相关的变量。我们称这个类为
CustomModel
。在 CustomModel
中,我有一个变量,比如说 $customVariable
,我需要对其执行 CRUD(创建、读取、更新、删除)操作。
php
class CustomModel extends \yii\db\ActiveRecord
{
public $customVariable;
// Other class properties and methods
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['customVariable'], 'safe],
];
}
}
public function actionCrud()
{
$model = new CustomModel();
if ($model->load(Yii::$app->request->post())) {
$model->save();
return $this->redirect(['custom-model/index']);
}
return $this->render('_form', [
'model' => $model,
]);
}
<?php $form = ActiveForm::begin([
'fieldConfig' => [
'template' => '{label}{input}{error}',
'errorOptions' => ['class' => 'error'],
'options' => [
'class' => 'form-group form-group-default'
],
],
]); ?>
<div class="row ">
<div class="col-md-6 col-xl-3">
<?php echo $form->field($model, 'customVariable')->textInput(['maxlength' => true]) ?>
</div>
</div>
<div class="form-group pull-right">
<?php echo Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
Active Record 始终映射到表列,模型本身代表单行。尝试更新与数据库表无关的随机变量是对 AR 模式的滥用。
我建议你使用DAO来更新随机表字段。