Yii: CActiveRecord::save方法保存记录提示Duplicate entry错误_Tomcat, WebLogic及J2EE讨论区_Weblogic技术|Tuxedo技术|中间件技术|Oracle论坛|JAVA论坛|Linux/Unix技术|hadoop论坛_联动北方技术论坛  
网站首页 | 关于我们 | 服务中心 | 经验交流 | 公司荣誉 | 成功案例 | 合作伙伴 | 联系我们 |
联动北方-国内领先的云技术服务提供商
»  游客             当前位置:  论坛首页 »  自由讨论区 »  Tomcat, WebLogic及J2EE讨论区 »
总帖数
1
每页帖数
101/1页1
返回列表
0
发起投票  发起投票 发新帖子
查看: 2709 | 回复: 0   主题:  Yii: CActiveRecord::save方法保存记录提示Duplicate entry错误        下一篇 
wongz
注册用户
等级:新兵
经验:46
发帖:55
精华:0
注册:2011-8-6
状态:离线
发送短消息息给wongz 加好友    发送短消息息给wongz 发消息
发表于: IP:您无权察看 2015-4-3 15:22:37 | [全部帖] [楼主帖] 楼主

在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()


--转自 北京联动北方科技有限公司




赞(0)    操作        顶端 
总帖数
1
每页帖数
101/1页1
返回列表
发新帖子
请输入验证码: 点击刷新验证码
您需要登录后才可以回帖 登录 | 注册
技术讨论