问题
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:
$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.
来源:https://stackoverflow.com/questions/2304280/cakephp-newbie-question-how-do-i-duplicate-a-model-and-its-related-data