CakePHP - Why does Model::save cause() an INSERT i

2019-01-28 15:31发布

问题:

I want to update database in CAKEPHP's Way this is my controller

$data = array(
'KnowledgeBase' => array(
'kb_title' => $this->data['KnowledgeBase']['kb_title'],
'kb_content' => $this->data['KnowledgeBase']['kb_content']
'kb_last_update' => date("Y-m-d G:i:s"),
'kb_segment' => $this->data['KnowledgeBase']['kb_segment']
));
$this->KnowledgeBase->id_kb = $this->data['KnowledgeBase']['id_kb'];
$this->KnowledgeBase->save($data);

assume I have post form is true, when I execute the program I have some error like this :

Database Error

 Error: SQLSTATE[23000]: [Microsoft][SQL Server Native Client 10.0]
[SQL Server]Violation of PRIMARY KEY constraint 'PK_cnaf_kb'.
 Cannot insert duplicate key in object 'dbo.cnaf_kb'.

SQL Query: INSERT INTO [cnaf_kb] ([kb_judul], [kb_segment], [kb_isi], [id_kb], [kb_last_update], [kb_status]) VALUES (N'HARRIS TEST 4 ', N'4', N'<p>TESSSSSSSSSSSSSSSSSSSSSS</p> ', 73, 
'2013-10-04 16:57:00', 1)

why the function use the insert query? not update ?

note : im not using form helper for post to controller, and I use Cakephp 2.3.8 version and sql server 2008 for database

Im sorry for my bad english, I hope someone can help me :(((

回答1:

You do not supply a primary key value, that's why.

No matter what your primary key is named (Model::$primaryKey), on the model object you have to use the id property (Model::$id) if you want to set the primary key value.

$this->KnowledgeBase->id = $this->data['KnowledgeBase']['id_kb'];

Internally the model maps this to the appropriate primary key field.

In the data however you'd use the actual primary key name:

'id_kb' => $this->data['KnowledgeBase']['id_kb']

btw, I'm not sure why you are (re)building the data array, but if it's to make sure that only specific fields are saved, then you could use the fieldList option instead:

$this->data['KnowledgeBase']['kb_last_update'] = date('Y-m-d G:i:s');

$options = array(
    'fieldList' => array(
        'kb_title',
        'kb_content',
        'kb_last_update',
        'kb_segment'
    )
);

$this->KnowledgeBase->save($this->data, $options);