D
D
Daniil Sidorov2017-09-16 20:43:47
Yii
Daniil Sidorov, 2017-09-16 20:43:47

How to add properties to model after save in Yii2?

Hello. I'm trying to add the current value of the date to the model when Create , but for some reason I always get null in the database.

public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);

        $this->date =  new \DateTime();
    }

The date is stored in the database as a DateTime . Where is the mistake?
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2017-09-16
@slo_nik

Good evening.
Use the behavior and everything will be fine.
Add the following code to the models:

use yii\behaviors\TimestampBehavior;

    public function behaviors()
    {
        return [

            TimestampBehavior::className()

        ];
    }

And in afterSave() delete everything

B
Boris Korobkov, 2017-09-16
@BorisKorobkov

First, not after (after saving), but before.
Secondly, better www.yiiframework.com/doc-2.0/yii-behaviors-timesta...
And for other fields (for example, user) www.yiiframework.com/doc-2.0/yii-behaviors-attribu...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question