1. 程式人生 > >Yii: CActiveRecord::save方法儲存記錄提示Duplicate entry錯誤

Yii: CActiveRecord::save方法儲存記錄提示Duplicate entry錯誤

    把

$videoTagModel = VideoTagModel::model();

    改成

$videoTagModel = new VideoTagModel();


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

示範如下:

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