Previously, the data submitted in yii1 was $ model-& amp; gt; load () $ model-& amp; gt; save () for example, if you want to convert the date type to the int type, it will be converted to $ this-& amp; gt; datetime () in beforesave () But beforeSave () in yii2 () {$ this-& amp; gt; datetime ()} will first...
Previously in yii1
Yes
$model->load()
$model->save()
For example, I want to convert the date type to the int type.
Will be in beforesave ()$this->date = time()
Conversion
But in yii2
BeforeSave (){
$ This-> date = time ()
}
The rule Method of validate will be taken first
That is to say, the beforeSave command is executed before the beforeSave command is converted. The beforeSave command is still in use.
Reply content:
Previously in yii1
Yes
$model->load()
$model->save()
For example, I want to convert the date type to the int type.
Will be in beforesave ()$this->date = time()
Conversion
But in yii2
BeforeSave (){
$ This-> date = time ()
}
The rule Method of validate will be taken first
That is to say, the beforeSave command is executed before the beforeSave command is converted. The beforeSave command is still in use.
If you just want to assign a value to the time field, we recommend that you add the following code to the model:
php
public function behaviors() { return [ [ 'class' => TimestampBehavior::className(), 'attributes' => [ ActiveRecord::EVENT_BEFORE_INSERT => ['created_at','updated_at'], ActiveRecord::EVENT_BEFORE_UPDATE => 'updated_at' ], ], }
Then I will reply to the landlord's question. The process is as follows:
flow
St => start: $ model-> save (runValidation) e => end: the entire request ends. runValidation => condition: runValidation? BeforeValidate => operation: Operator => operation: validate (run rules here) afterValidate => operation: afterValidatebeforeSave => operation: beforeSavesave => operation: saveafterSave => operation: afterSavest-> runValidationrunValidation (yes, right)-> beforeValidaterunValidation (no)-> validate-> afterValidate (left)-> beforeSavebeforeSave-> save-> afterSave-e
I went here. In order to draw this flowchart, I took a special look.markdown
Flow chart syntax... One night is in vain... You are responsible
Try this:
public function beforeSave($insert){ if (parent::beforeSave($insert)) { $this->date = time(); return true; } else { return false; }}
I don't know what troubles the subject is, but if you have to leaverules()
, You can directlysave()
Method specified$runValidation
Isfalse
RTFM
Http://www.yiiframework.com/doc-2.0/yii-db-baseactiverecord.html#save (...