Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

php - CakePHP - Why does Model::save cause() an INSERT instead of an UPDATE?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...