V
V
Vladimir2017-09-26 15:13:20
MySQL
Vladimir, 2017-09-26 15:13:20

Why is the data not saved correctly in the Yii2 database?

Good day! There is a table with a field "from_form" tiny_int(1). Here is the action:

public function actionView($id)
{
    $model = $this->findModel($id);
    if ($model->from_form > 2) {
        $new_model = Mails::findOne($id);
        $new_model->from_form = $model->from_form - 2;
        $new_model->save();
    }

    return $this->render('view', [
        'model' => $model,
    ]);
}

I want that when the record is opened, there would be a check and if true , then subtract 2 from this number and write it to the database. Initially, the database has a from_form field with a value of 4. That is, logically, when opening, it should be 4 - 2 = 2 and write 2 to the database. But for some reason it is recorded 3-a. Even if I write $new_model->from_form = 2;, 3 is still recorded. Tell me what am I doing wrong? If you need any more information, write in the comments, I will supplement. Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2017-09-26
@MasterGerold

Good afternoon.
Move these calculations to the model, to the beforeSave() method, and slightly change the line with the PS calculation. It should look something like this:

public function beforeSave($insert)
{
  if(parent::beforeSave($insert)){
    if((self::getOldAttribute('from_form') > 2){
        $this->from_form = ($this->from_form - 2)
        }
    return true;
  }
  return false;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question