CakePHP新手问题:如何复制模型及其相关数据? [英] CakePHP newbie question: How do I duplicate a model and its related data?
问题描述
如何复制现有模型记录?换句话说,如何使用相关数据检索现有模型,然后保存该模型和数据的COPY(模型和相关数据是否都已复制)?这是很简单的使用简单的SQL,但我想使用CakePHP最佳做法。
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.
推荐答案
$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);
基本上,你需要确保没有 id
字段包含在数据中,然后只是像往常一样保存。
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.
根据您的具体数据,编写 INSERT ... SELECT ...
使用 $ Model-> query()
直接查询。
Depending on your specific data, it may be more economic to write an INSERT … SELECT …
query directly using $Model->query()
though.
这篇关于CakePHP新手问题:如何复制模型及其相关数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!