Yii的 - CDbCommand未能执行SQL语句:SQLSTATE [23000]:完整性约束违规:1062重复项“5375”重点“主要” [英] Yii - CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '5375' for key 'PRIMARY'

查看:1267
本文介绍了Yii的 - CDbCommand未能执行SQL语句:SQLSTATE [23000]:完整性约束违规:1062重复项“5375”重点“主要”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正与Yii的1.1.x和碰到下面的错误。

I am working with Yii 1.1.x and get the following error when performing an insert.

CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: 
Integrity constraint violation: 1062 Duplicate entry '5375' for key 'PRIMARY'

这发生在一个名为competition_prizes'表 - 只有一种叫'身份证'(没有其他指标或类似的东西)主键

This happens on a table called 'competition_prizes' - there is only one primary key called 'id' (there are no other indexes or anything like that).

我可以看到,有一排与5375的ID,以便项不存在(按照插入查询)。

I can see that there is one row with the id of 5375 so that entry does already exist (as per the insert query).

控制器code是如下具有内afterSave()功能的一些功能。

The controller code is as follows has some functionality within the afterSave() functionality.

protected function setPrizes($prizes, $prize_type)
{
    if(!empty($prizes) && is_array($prizes))
    {
            $prize_model = CompetitionPrizes::model();
            $competition_id = $this->competition_id;
            $prize_model->deleteAll('competition_id =:competition_id AND  prize_type = :prize_type ',array(
            ':competition_id'=> $competition_id,
            ':prize_type'=> $prize_type
            ));

            foreach($prizes as $prize_position => $prize_desc) :
                $prize_model->setIsNewRecord(true);
                $prize_model->setAttributes(compact('competition_id', 'prize_position', 'prize_type','prize_desc'));
                $prize_model->save();
            endforeach;
    }   
}

如何解决该错误的任何想法 - 请注意,我是新来的Yii如此温柔:)

Any ideas of how to get around the error - please note I'm new to Yii so be gentle :)

推荐答案

在的 $ prize_model-&GT顶; setIsNewRecord(真)(或 $ prize_model-> isNewRecord =真),你还必须空出id属性。正如我所提到的在我的评论所述,setIsNewRecord唯一确定甲醚的插入或更新方案时,当你调用保存()。如果你的PK仍被设置它只会尝试与设置这些值插入,从而导致重复的误差。

On top of the $prize_model->setIsNewRecord(true) (or $prize_model->isNewRecord = true) you also have to empty out the id attribute. As I've mentioned in my comment above, the setIsNewRecord only determines if ether the insert or update scenario is used when you call save(). If your PK is still set it will simply attempt an insert with those values set, resulting in a duplicate error.

下面应该做的伎俩:

$id = NULL;
foreach($prizes as $prize_position => $prize_desc) :
   $prize_model->setIsNewRecord(true);
   $prize_model->setAttributes(compact('id', 'competition_id', 'prize_position', 'prize_type','prize_desc'));
   $prize_model->save();
endforeach;

这篇关于Yii的 - CDbCommand未能执行SQL语句:SQLSTATE [23000]:完整性约束违规:1062重复项“5375”重点“主要”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆