Question

I'm using CakePHP 1.3, and I am inserting new records (a few ~ thousands) in a loop if it's new or updating existing records if they exist already. But the way I'm saving does not check for whether or not the record already exist; instead, I assign a primary key value in each of the records. This ID that I assign is guaranteed to be unique. CakePHP seems to know to insert if this ID does not exist and update otherwise.

However, I'm not sure if I'm doing it the right way. I read here if I'm creating a new record in a loop, I need to do $this->create(), which I do implement in other functions where I know each record is going to be unique. I don't do it here because it seems to work without errors, and I don't need to then check for each of the record's existence.

Each of the record array that I'm inserting or updating has the key id that indicate the primary key in the respective tables, and each array contains data for two models that are properly associated.

e.g.

$this->saveAll($myData);

Array
(
    [MyModel] => Array
    (
        [id] => 123
        [xyz] => ...
        ...
    )
    [MySecondModel] => Array
    (
        [id] => 789
        [my_model_id] => 123
        [qwe] => ...
        ...
    )
)

Is what I'm doing good, or do I need to check for existence followed by $this->create(), if necessary?

Was it helpful?

Solution

If you turn on SQL debugging, you will see that Cake fetches the record from the database if you specify an ID before save(). If the record exists Cake will perform an update, otherwise an insert; specifying a NULL for the ID forces an insert. So what you are doing is fine.

The create() is important if you are not filling all columns; otherwise data will remain in the object and you end up spilling data from one record to the other. create simply resets the internal data structure.

You don't need to check for existence of your data after save(), unless you're really paranoid. However, do check the result from save(); if it returns false something went wrong.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top