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

陌路散爱 提交于 2020-01-04 03:59:09

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!