现在的位置: 首页 > 综合 > 正文

Yii: CActiveRecord::save方法保存记录提示Duplicate entry错误

2014年04月02日 ⁄ 综合 ⁄ 共 810字 ⁄ 字号 评论关闭

在Yii中,使用CActiveRecord::save()方法保存数据,

对于新记录会使用insert into语句,而对于已有记录,会使用update语句。

参见Yii的说明:

"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.) 

"

但是如果你在save的时候遇到了如下错误:

“CDbCommand::execute() failed: SQLSTATE[23000]: Integrity constraint
violation: 1062 Duplicate entry '1' for key 'PRIMARY'.”

那么表示,你想更新某主键已存在的记录数据,但实际调用了insert语句。

原因一般是忽略了model构造时候的$scenario参数,构造model时Yii默认使用insert场景,所以要达到更新的效果需要把该参数置为null。

示范如下:

$profile = new UserProfile(null);//注意这里不能是new UserProfile();
$profile->user_id = 1; //这里user_id是Primary Key
$profile->address = 'demo';
$profile->updated = date('Y-m-d H:i:s');
$profile->save()

by iefreer

抱歉!评论已关闭.