如何正确地将数据保存到数据库? [英] How do I properly save data to the database?
问题描述
我通常将新数据保存到数据库,如下所示:
I normally save new data to the database like this:
$this->MyTable->set(array(
'id' => $id,
'code' => $temp_code,
'status' => $status,
'age' => $age,
'location' => $location,
'money' => $money
));
$this->MyTable->save();
如果数据库中已存在ID,则更新其相应的字段,如下所示:
If the ID already exists in the database I update its corresponding fields like this:
$this->Adtweet->id = $id;
$this->Adtweet->saveField('code', $temp_code);
$this->Adtweet->saveField('status', $status);
有更好的或正确的方法吗?
Is there a better or 'proper' way to do this?
当我尝试输入已经存在的ID并且使用 set
函数时,我得到以下SQL完整性错误:
When I attempt to enter an ID that already exists and I use the set
function, I get the following SQL integrity error:
(错误:SQLSTATE [23000]:完整性约束违例:1062键'PRIMARY'的重复条目'150245925')
(Error: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '150245925' for key 'PRIMARY')
如何编写一个干净处理重复条目而不返回错误的函数?
How can I write a function that cleanly handles duplicate entries without returning an error?
推荐答案
如果要保存新数据,只需使用 Model :: save()
:
$data = array(
'ModelName' => array(
'foo' => $foo
)
)
// prepare the model for adding a new entry
$this->ModelName->create();
// save the data
$this->ModelName->save($data);
如果要更新数据,只需使用相同的方法,而不调用 Model :: create()
If you want to update your data just use the same method without calling Model::create()
$data = array(
'ModelName' => array(
'id' => $id
'foo' => $foo
)
)
$this->ModelName->save($data);
修改:
我想这是您要查找的内容:
I guess this is what you're looking for:
$this->ModelName->id = $id;
if (!$this->ModelName->exists()) {
$this->ModelName->create();
}
$this->ModelName->save($data);
这篇关于如何正确地将数据保存到数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!