Yii2:对与数据库表无关的类内的变量执行CRUD操作

问题描述 投票:0回答:1

问题陈述

我目前正在开发一个 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],
        ];
    }
}

我在 CustomModelController 中尝试过的内容

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(); ?>

但是尽管成功提交了表单,它并没有更新变量

php model-view-controller yii2 yii2-advanced-app
1个回答
0
投票

Active Record 始终映射到表列,模型本身代表单行。尝试更新与数据库表无关的随机变量是对 AR 模式的滥用。

我建议你使用DAO来更新随机表字段。

© www.soinside.com 2019 - 2024. All rights reserved.