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。
示范如下:
by iefreer
对于新记录会使用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
相关文章推荐
- Yii: CActiveRecord::save方法保存记录提示Duplicate entry错误
- Hibernate: Session对象中的两个保存记录的方法 save vs. persist
- android onSaveInstanceState方法 横坚屏切换的状态保存
- hibernate中各种保存方法的区别 save persist update saveOrUpdate merge lock
- Yii CActiveRecord 扩展(万金油列支持)
- 腾讯通rtx不能保存聊天记录的解决方法
- 如何使用web_reg_save_param方法保存的多个参数?
- DreamWeaver文件保存时,提示"发生共享违例"问题的解决方法
- Yii之Active Record find()方法
- Yii 2.0常用方法记录
- Win10运行记录不保存了,Win键+R运行没有历史记录解决方法
- C# WebBrower1控件提示“该文档已被修改,是否保存修改结果”解决方法
- 如何使用web_reg_save_param方法保存的多个参数?
- Yii框架实现记录日志到自定义文件的方法
- 用mysql编写在BORROW表上建立一个触发器,完成将该读者的借阅记录保存在BORROW_SAVE表中。。
- Win10 15063 开始运行不保存历史记录原因和解决方法
- C# 保存excel 问题 ,save 方法
- lync本地聊天记录修改目录保存的方法
- yii save后获取保存数据的id
- IE浏览器下载excel文件时不弹出下载保存提示框的解决方法