Question

This is essentially the same question as CakePHP: Is it possible to insert record with pre-defined primary key value?. In CakePHP 1.2 I want to insert a record with a pre-determined id. The id's value is determined by an external system, but unlike in the linked question I have no control over that system, so the solution to that question is not an option for me.

If the id field of a model is set when calling $model->save(), Cake will always try to update the record. Cake will even set the id to false, if a record with that id does not exist already [1]:

<?php
function save($data = null, $validate = true, $fieldList = array()) {
    // snip
    if (!$this->__exists && $count > 0) {
        $this->id = false;
    }
    // snip
}

Saving the model first and then updating the id manually is also not an option, because this would break referencial integrity (this is an architectural limitation that I also have no control over).

So how can I force CakePHP to insert the record with a specific primary key?

Some background around the problems I'm facing:

The application I'm working on is backed by a Postgres database, so new primary keys are determined by sequences. There is a process where an external system will SELECT nextval('my_model_sequence'), do some work with that id and then pass it to the CakePHP application, where I want to INSERT a my_model record with that id.

There is no way for me to invoke the external process after saving the record. There is also no way for me to modify the external process at all.


[1] http://api12.cakephp.org/view_source/model/#l-1260

Was it helpful?

Solution

If you want to create a record with specific id just make sure you fill id field

   $this->data['ModelName']['id'] = $your_id;

Also before calling:

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

you should remember to call

$this->create();

which will reset the model state which let you create new record. Finally you should try:

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

On the other hand as I read your post and trying to imagine your tables structure I recommend you thinking over leaving the id field alone and trying to make this foreing id a Foreign key. Is that an option for you?

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