yii activerecord save()方法出错的问题

在用YII框架做微信平台开发的时候发现一个很奇怪的问题,通过activerecord 在model中直接做$this->save()的时候,返回true,通过getErrors()返回也为空。但是数据没插入数据库。另外极客导航是自己写的框架没用YII,虽然对YII比较了解,但抱着学习的态度还是从写了一个框架。希望大家能多给反馈问题!

代码如下:

1
2
3
4
5
6
public function insertReceive($arr)  
{
$this->receive\_id = $arr->ToUserName;
$this->tm = $arr->CreateTime;
$this->save();
}

如果你在model 的某个方法中直接执行了$this->save()语句,系统不会报错,但实际上是没执行成功的。为什么会这样?难道是YII框架的bug?

我们先看官方文档对于save()方法的解释

Saves the current record.
The record is inserted as a row into the database table if its isNewRecord property is true (usually the case when the record is created using the ‘new’ operator). Otherwise, it will be used to update the corresponding row in the table (usually the case if the record is obtained using one of those ‘find’ methods.)
Validation will be performed before saving the record. If the validation fails, the record will not be saved. You can call getErrors() to retrieve the validation errors.
If the record is saved via insertion, its isNewRecord property will be set false, and its scenario property will be set to be ‘update’. And if its primary key is auto-incremental and is not set before insertion, the primary key will be populated with the automatically generated key value.

挑选重点翻译:
在使用save方法时,如果当前model对象的isNewRecord属性是true,就会插入数据。否则就会更新数据。如果是通过new方法实例化对象,isNewRecord默认是true,如果使用了find或者find衍生的方法,isNewRecord默认是false;

如果没用new也没用find,isNewRecord默认也是false,执行update时找到的数据为空,所以无法更新。但是流程是通的所以不会报错。

最后修改后的代码如下:

1
2
3
4
5
6
7
public function insertReceive($arr)  
{
$this->receive\_id = $arr->ToUserName;
$this->tm = $arr->CreateTime;
$this->setIsNewRecord(true);
$this->save();
}

真是细节决定代码啊!