2013-07-10 26 views
0

我使用CakePHP v2.3.5。當我更新模型 - >保存()始終使用'插入'即使身份證

`users` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT, 
    `email` varchar(320) NOT NULL, 
    `password` varchar(45) NOT NULL, 
    `firstname` varchar(255) DEFAULT NULL, 
    `lastname` varchar(255) DEFAULT NULL, 
    `country` varchar(255) DEFAULT 'SG', 
    PRIMARY KEY (`id`) 
); 

使用$this->User->save($this->request->data)表,它總是觸發一個INSERT命令,並拋出

"Integrity constraint violation: 1062 Duplicate entry '10' for key 'PRIMARY'" 

request->data對象是:

array(
    'User' => array(
     'id' => '10', 
     'firstname' => 'Someone', 
     'lastname' => 'Surname', 
    ) 
) 

我現在使用的完整行動是:

public function addInfo() { 
    if ($this->request->is('post')) { 

     $this->User->create(); 
     $this->User->id=(int)$this->request->data['User']['id']; 
     if ($this->User->save($this->request->data)) { 

     } 

    } 
} 

,並在型號的beforeSave功能是:

公共函數beforeSave($選項=陣列()){

if (isset($this->data['User']['password'])) { 
     $this->data['User']['password'] = AuthComponent::password($this->data['User']['password']); 
    } 
    return true; 

}

在用戶對象,此ID =>假看起來很腥

object(User){ displayField > '姓名' 的PrimaryKey =>的 'id' useDbConfig => '缺省' useTable => '用戶' ID =>假 數據=>數組( [最大深度達到] ) }

+0

嘗試在'request-> data'數組中使用''id'=> 10'(10爲整數) – Nunser

+0

感謝您編輯帖子。將id作爲整數'User'=> array('id'=>(int)10,'firstname'=>'Someone','lastname'=>'姓氏'),但問題仍然存在。 – user2078719

+1

請顯示您的整個控制器操作代碼。只是引用您正在使用的保存方法不會幫助我們幫助您。 – Oldskool

回答

0

找到原因。我碰巧在模型中有一個名爲getId的函數,而CakePHP也使用getId來檢查該行的存在,因此,它在檢查id時總是得到否定結果,因此它觸發了插入調用而不是更新調用。感謝大家的幫助。

0

如果要更新的值,而不是創建一個新的,請確保您逝去的主鍵字段到數據數組:

$data = array('id' => 10, 'firstname' => 'Someone', 'lastname'=> 'Surname'); 
// This will update User with id 10 

$this->User->save($data); 
+0

不,我想更新行,所以我沒有'創建'記錄。如果我沒有錯,'創建'是爲了'插入'行動。 – user2078719

+0

啊對不起,我誤解了這個問題,我改變了我的回答 –

+0

它仍然解僱了'insert'sql查詢。 – user2078719

0

嘗試保存之前設置ID:

$this->User->id = useridhere 
$this->Users->save($this->request->data); 
+0

嘗試添加$ this-> User-> id =(int)$ this-> request-> data ['User'] ['id'];保存之前。並且測試了$ this-> User-> exists($ this-> request-> data ['User'] ['id'])return 1.但仍然'insert'sql而不是'update' – user2078719

1

做了創建節約

$this->User->create(); 
$this->User->save($this->request->data); //with the id cast as integer 

create是正在重置模型前,所以即使它是一個更新,你應該調用該函數作爲預防措施。

+0

它仍然觸發'插入具有「完整性約束違規」錯誤的查詢。 – user2078719

0

我在這裏遇到同樣的問題。我嘗試了不同的配置(使用save(),saveAll(),saveMany(),saveAssociated(),選項),後來我發現我的表具有不同的主鍵(主字段名稱不是「ID」)。將主要字段名稱添加到我的模型可以解決問題。

class SomeModel extends AppModel { 

    public $primaryKey = "different_primary_field_name_for_id"; 

} 
相關問題