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

在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。

示范如下:

[php]  view plain  copy
  1. $profile = new UserProfile(null);//注意这里不能是new UserProfile();  
  2. $profile->user_id = 1; //这里user_id是Primary Key  
  3. $profile->address = 'demo';  
  4. $profile->updated = date('Y-m-d H:i:s');  
  5. $profile->save()  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值