How do I properly save data to the database?

佐手、 提交于 2019-12-18 17:38:27

问题


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:

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

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


回答1:


If you want to save new data, just use 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()

$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

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



回答2:


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


来源:https://stackoverflow.com/questions/11127210/how-do-i-properly-save-data-to-the-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!