views:

144

answers:

1

How do I duplicate an existing model record? Put another way, how do I retrieve an existing model with related data, then save a COPY of that model AND data (both model and related data are copied)? This is trivial using simple SQL, but I want to do it using CakePHP best practices.

+1  A: 
$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'll want to make sure there are no id fields included in the data, then just save it as usual. That will prompt Cake to create a new record.

Depending on your specific data, it may be more economic to write an INSERT … SELECT … query directly using $Model->query() though.

deceze
Many thanks -- I'll give it a try. It will almost certainly more economic to use the direct query, but I'd like to try and do it the "CakePHP way". -- Steve
Steve