之前在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还有毛用了
如果楼主是单纯想要给时间字段赋值,建议在模型里添加如下代码:
phppublic function behaviors() { return [ [ 'class' => timestampbehavior::classname(), 'attributes' => [ activerecord::event_before_insert => ['created_at','updated_at'], activerecord::event_before_update => 'updated_at' ], ], }
然后我再正面回答一下楼主问题,流程如下:flowst=>start: $model->save(runvalidation)e=>end: 整个请求结束runvalidation=>condition: runvalidation?beforevalidate=>operation: beforevalidatevalidate=>operation: validate(rules在这儿执行)aftervalidate=>operation: aftervalidatebeforesave=>operation: beforesavesave=>operation: saveaftersave=>operation: aftersavest->runvalidationrunvalidation(yes,right)->beforevalidaterunvalidation(no)->beforesavebeforevalidate->validate->aftervalidate(left)->beforesavebeforesave->save->aftersave->e
我勒个去,为了画这个流程图,我专门去看了下markdown的流程图语法。。。一晚上时间就白费了。。。楼主,你要负责
这样写试试:
public function beforesave($insert){ if (parent::beforesave($insert)) { $this->date = time(); return true; } else { return false; }}
不知道题主是什么困扰,但是你如果是非得不走rules(),可以直接在save()方法指定$runvalidation为false
rtfm
http://www.yiiframework.com/doc-2.0/yii-db-baseactiverecord.html#save(...