您的位置:首页 > 编程语言 > PHP开发

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

2014-02-27 01:33 501 查看
在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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: