我想以 CAKEPHP 的方式更新数据库这是我的控制器
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 ?
注意:我没有使用表单助手来发布到控制器,我使用 Cakephp 2.3.8 版本和 sql server 2008 作为数据库
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
) 如果要设置主键值.
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']
顺便说一句,我不确定您为什么要(重新)构建 data
数组,但是如果要确保仅保存特定字段,那么您可以使用 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);
这篇关于CakePHP - 为什么 Model::save cause() 是 INSERT 而不是 UPDATE?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!