Home > Backend Development > PHP Tutorial > yii2 的model 执行流程是什么

yii2 的model 执行流程是什么

WBOY
Release: 2016-06-06 20:30:33
Original
1247 people have browsed it

之前在yii1里

提交数据是
$model->load()
$model->save()
比如我要把 date类型转为int类型
会在 beforesave()里 $this->date = time() 转换

但是在yii2里

beforeSave(){
$this->date = time()
}

会先走validate的 rule方法

就是说 没有进beforeSave转换之前就先执行了, 那beforeSave还有毛用了

回复内容:

之前在yii1里

提交数据是
$model->load()
$model->save()
比如我要把 date类型转为int类型
会在 beforesave()里 $this->date = time() 转换

但是在yii2里

beforeSave(){
$this->date = time()
}

会先走validate的 rule方法

就是说 没有进beforeSave转换之前就先执行了, 那beforeSave还有毛用了

如果楼主是单纯想要给时间字段赋值,建议在模型里添加如下代码:

<code>php</code><code>public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['created_at','updated_at'],
                    ActiveRecord::EVENT_BEFORE_UPDATE => 'updated_at'
                ],
            ],
    }
</code>
Copy after login

然后我再正面回答一下楼主问题,流程如下:

<code>flow</code><code>st=>start: $model->save(runValidation)
e=>end: 整个请求结束
runValidation=>condition: runValidation?
beforeValidate=>operation: beforeValidate
validate=>operation: validate(rules在这儿执行)
afterValidate=>operation: afterValidate
beforeSave=>operation: beforeSave
save=>operation: save
afterSave=>operation: afterSave

st->runValidation
runValidation(yes,right)->beforeValidate
runValidation(no)->beforeSave
beforeValidate->validate->afterValidate(left)->beforeSave
beforeSave->save->afterSave->e
</code>
Copy after login

我勒个去,为了画这个流程图,我专门去看了下markdown的流程图语法。。。一晚上时间就白费了。。。楼主,你要负责

这样写试试:

<code>public function beforeSave($insert)
{
    if (parent::beforeSave($insert)) {
        $this->date = time();
        return true;
    } else {
        return false;
    }
}
</code>
Copy after login

不知道题主是什么困扰,但是你如果是非得不走rules(),可以直接在save()方法指定$runValidationfalse

RTFM

http://www.yiiframework.com/doc-2.0/yii-db-baseactiverecord.html#save(...

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template