牛骨文教育服务平台(让学习变的简单)
博文笔记

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

创建时间:2014-02-27 投稿人: 浏览次数:128

在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

声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。