問題描述
我想以 CAKEPHP 的方式更新數(shù)據(jù)庫這是我的控制器
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);
假設(shè)我的帖子形式是真的,當(dāng)我執(zhí)行程序時我有一些這樣的錯誤:
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)
為什么函數(shù)使用插入查詢?不更新?
why the function use the insert query? not update ?
注意:我沒有使用表單助手來發(fā)布到控制器,我使用 Cakephp 2.3.8 版本和 sql server 2008 作為數(shù)據(jù)庫
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 :(((
推薦答案
您沒有提供主鍵值,這就是原因.
You do not supply a primary key value, that's why.
不管你的主鍵叫什么(Model::$primaryKey
),在模型對象上你必須使用 id
屬性(Model::$id
) 如果要設(shè)置主鍵值.
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'];
模型在內(nèi)部將其映射到適當(dāng)?shù)闹麈I字段.
Internally the model maps this to the appropriate primary key field.
在數(shù)據(jù)中,您將使用實際的主鍵名稱:
In the data however you'd use the actual primary key name:
'id_kb' => $this->data['KnowledgeBase']['id_kb']
順便說一句,我不確定您為什么要(重新)構(gòu)建 data
數(shù)組,但是如果要確保僅保存特定字段,那么您可以使用 fieldList
選項 代替:
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);
這篇關(guān)于CakePHP - 為什么 Model::save cause() 是 INSERT 而不是 UPDATE?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!