trante trante - 6 months ago 48
MySQL Question

CakePHP saving data to database

In CakePHP 2 I enter new data to database like this:

$this->MyTable->set(array(
'id' => $id,
'code' => $temp_code,
'status' => $status,
'age' => $age,
'location' => $location,
'money' => $money
));

$this->MyTable->save();


If that ID already exist in database I update fields like this:

$this->Adtweet->id = $id;
$this->Adtweet->saveField('code', $temp_code);
$this->Adtweet->saveField('status', $status);



  • Is this the proper way, or is there better way?

  • But if that ID exists in database and I use "set" function I get SQL integrity error (Error: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '150245925' for key 'PRIMARY')



How can i write a proper function that handles even the ID exists or doesn't exist in database?
Thank you

Answer

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