如何使用活动记录字段创建类的对象?

时间:2017-05-07 15:24:57

标签: php yii2

我有一个只有2个参数的简单模型 - 'sum'和'name'。我创建了这个模型类的新对象并将其发送到视图。在视图中我有两个字段 - 也是'sum'和'name'。 当我在字段中输入值(fe sum = 10,name = Joe)时,我希望我的当前总和将减少10,但对于用户Joe,它将增加10.(数据库中还有三列 - 'id',' sum'和'name')。 但我无法从字段中传输此名称以更新数据库。

//Controller
public function actionSum()
{
    $model = new SumForm();
    if ($model->load(Yii::$app->request->post())) {
        if ($user = $model->sumfunction()) {
        } return $this->goHome();
    }
    return $this->render('sum', [
        'model' => $model,
    ]);
}

//Model
class SumForm extends Model
{
public $sum;
public $name;


public function attributeLabels()
{
    return [
        'sum' => 'Sum',
        'name' => 'Name',
    ];
}

public function sumfunction()
{
    if ($this->validate()) {
        $desc = User::findOne(Yii::$app->user->getId());
        $desc->sum -= $this->sum;
        $desc->save();
        $inc = User::findOne(['name'=>Yii::$app->request->post('name')]);
        //here I need to take a row for user which name I input
        $inc->sum += $this->sum;
        $inc->save();
    }
}

//in view 'sum' only two fields and button

1 个答案:

答案 0 :(得分:0)

使用ActiveRecord时,您将获得附加到模型的参数。在这种情况下,SumForm [name]

使用它的最佳方式:

  $inc = User::findOne(['name' => $this->name]);
  $inc->sum += $this->sum;
  $inc->save(false); //without validation! Fix it later.

并添加SumForm:

public function rules()
{
    return [
        [['name'], 'string'],
        [['sum'], 'safe'],
    ];
}

并显示您的用户模型。还必须有属性名称和总和的验证器。

并在actionSum()中更改:

// if ($model->load(Yii::$app->request->post())) {
if ($model->load(\Yii::$app->request->post()) && $model->validate()) {

如果模型验证失败,您将在表单中看到错误。

形式:

<?php $form = ActiveForm::begin(); ?>

<?= $form->field($model, 'name')->textInput() ?>
<?= $form->field($model, 'sum')->textInput() ?>

<?= Html::submitButton('confirm') ?>
<?php ActiveForm::end(); ?>