3

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?

Lemmings19
  • 1,383
  • 3
  • 21
  • 34
trante
  • 33,518
  • 47
  • 192
  • 272

2 Answers2

19

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);
Julian Hollmann
  • 2,902
  • 2
  • 25
  • 44
  • Thank you for reply. To use "create" I think I should make something like this: Because before checking the model, I don't know even that ID exists in database or not.. `$isIdExists = $this->ModelName->find('first', array( 'conditions' => array('ModelName.id' => $id)` --- `if ($isIdExists) { $this->ModelName->create(); }` – trante Jun 20 '12 at 20:15
  • Thank you for update. When i tried `$this->ModelNAme->create();`, a row with ID zero is created. But I have a proper ID of user. So i changed it like this `$this->ModelName->create( array ('id' => $id));` This created proper row. But after that `!$this->ModelName->exists()` still gives true.. I suppose I should work more and more.. – trante Jun 20 '12 at 20:47
  • 3
    Maybe you forgot to set the ID column to `auto_increment`? – Julian Hollmann Jun 20 '12 at 20:53
  • Well, I use this model for the member data. So ID column is twitter ID of user. Every user has unique twitter ID and it doesn't start from zero. So I create new record with ID parameter, if it doesnt exist. – trante Jun 20 '12 at 20:58
  • Now I'm dealing with this: `$this->ModelName->twitter_user_id = $twitter_user_id;` `$isIdExists = $this->ModelName->exists();` in this case `$isIdExists` returns false. But from phpmyadmin I can see that, the record is there – trante Jun 20 '12 at 21:00
  • 1
    The main problem here is, that cakephp expects the primary key is called 'id', if this isn't the case you need to tell this your model. So if your primary key field is called "twitter_user_id" you have to set `public $primaryKey = 'twitter_user_id';`in your model. – Julian Hollmann Jun 20 '12 at 21:04
  • primaryKey info helped me very much thank you. Sorry for disturbing you. Is it possible to stop active record in a for loop? In the code below, "arrayOfIds" has 4 elements. When I run it, in first loop ($arrayOfIds[0]) `$this->ModelName->exists()` comes false, and new row is created. Then in next loops, for example $arrayOfIds[1], `$this->ModelName->exists()` comes true, although the Id of them are different and not exist in table. First loop result is OK, in next loop ti lacks. – trante Jun 20 '12 at 21:36
  • `foreach ($arrayOfIds as $twitter_user_id) { $this->ModelName->twitter_user_id = $twitter_user_id; if ($this->ModelName->exists()) { echo "$twitter_user_id exists
    "; } else { echo "$twitter_user_id not exists
    "; $this->ModelName->create( array ('twitter_user_id' => $twitter_user_id)); } $data = array('ModelName' => array('age' => 15, 'last_satatus' => 'online' )); $this->ModelName->save($data); }`
    – trante Jun 20 '12 at 21:36
  • I suppose **create** with parameter **false** resets current active record. http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-create-array-data-array – trante Jun 21 '12 at 04:00
  • For further questions please close this one and open a new one. – Julian Hollmann Jun 21 '12 at 07:04
0

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);
 }
Sunil kumar
  • 761
  • 5
  • 15