简体   繁体   English

如何正确地将数据保存到数据库?

[英]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();

If the ID already exists in the database I update its corresponding fields like this: 如果数据库中已存在该ID,我将更新其相应的字段,如下所示:

$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? 有没有更好或“正确”的方法来做到这一点?

When I attempt to enter an ID that already exists and I use the set function, I get the following SQL integrity error: 当我尝试输入已存在的ID并使用set函数时,我收到以下SQL完整性错误:

(Error: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '150245925' for key 'PRIMARY') (错误:SQLSTATE [23000]:完整性约束违规:1062重复条目'150245925'用于键'PRIMARY')

How can I write a function that cleanly handles duplicate entries without returning an error? 如何编写一个干净地处理重复条目而不返回错误的函数?

If you want to save new data, just use Model::save() : 如果要保存新数据,只需使用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);

If you want to update your data just use the same method without calling Model::create() 如果要更新数据,只需使用相同的方法,而无需调用Model::create()

$data = array(
    'ModelName' => array(
        'id' => $id
        'foo' => $foo
    )
)

$this->ModelName->save($data);

See also: http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-save-array-data-null-boolean-validate-true-array-fieldlist-array 另见: http//book.cakephp.org/2.0/en/models/saving-your-data.html#model-save-array-data-null-boolean-validate-true-array-fieldlist-array

Edit: 编辑:

I guess this is what you're looking for: 我想这就是你要找的东西:

$this->ModelName->id = $id;
if (!$this->ModelName->exists()) {
    $this->ModelName->create();
}

$this->ModelName->save($data);

Posted data example 发布数据示例

Array
(
    [ModelName] => Array
        (
            [column1] => value
            [column2] => value
            [column3] => value
        )

)

Try this to add 试试这个添加

if ($this->request->is('post')) {
    $this->ModelName->create();
    $this->ModelName->save($this->request->data);
}

Try this to edit 试试这个来编辑

if ($this->request->is('post')) {
    $this->ModelName->id = 2;
    $this->ModelName->save($this->request->data);
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM