CakePHP newbie question: How do I duplicate a model and its associated data?

How to duplicate an existing model record? In other words, how to get an existing model with related data, and then save a COPY of this model AND data (how to copy both the model and the associated data)? This is trivial using plain SQL, but I want to do it using the best CakePHP methods.

+3
source share
1 answer
$record = $this->Model->find('first', array('condition' => array('Model.id' => $id)));
unset($record['Model']['id'], $record['RelatedModel']['id'], /* further ids */);
$this->Model->create();
$this->Model->saveAll($record);

Basically, you want to make sure that there are no fields in the data id, and then just save them as usual. This will force Cake to create a new entry.

INSERT … SELECT … , $Model->query(), .

+4

Source: https://habr.com/ru/post/1733718/


All Articles