$original = $this->Table->get($id)->toArray();
$copy = $this->Table->newEntity();
$copy = $this->Table->patchEntity($copy, $original);
unset($copy['id']);
// Unset or modify all others what you need
$this->Table->save($copy);
// load the models
$this->loadModel('Questionnaire');
$this->loadModel('Questions');
// get the questions to questionnaire association - will need the PK name
$qAssoc = $this->{'Questions'}->associations()->get('Questionnaire');
// get the existing entity to copy
$existingEntity = $this->{'Questionnaire'}->get($id, [
'contain' => ['Questions'],
]);
// clean up the existing entity
$existingEntity->unsetProperty($this->{'Questionnaire'}->getPrimaryKey());
$existingEntity->unsetProperty('created');
$existingEntity->unsetProperty('modified');
// clean up the associated records of the existing entity
foreach ($existingEntity->questions as &$q) {
$q->unsetProperty($this->{'Questions'}->getPrimaryKey());
$q->unsetProperty($qAssoc->getForeignKey());
}
// create a new entity and patch it with source data
$newEntity = $this->{'Questionnaire'}->patchEntity(
$this->{'Questionnaire'}->newEntity(),
$existingEntity->toArray()
);
// save the new entity
$result = $this->{'Questionnaire'}->save($existingEntity);
5条答案
按热度按时间wydwbb8l1#
我认为最好的方法是遵循工作流程:
1.获取要克隆对象
1.检查集合并删除所有ID
1.转换为数组并在
$this->Questionnaires->newEntity($arrayData, ['associated' => ['Questions', '...']]);
中使用1.现在,保存新实体以及要保留的所有相关数据
AFAIK没有“更聪明”的方法来克隆蛋糕3中的关联实体:-)
gpfsuwkq2#
您也可以使用this plugin。您只需要配置行为,它就可以为您提供其他功能,比如设置默认值或向某些字段追加文本。
kcwpcxri3#
使用EntityInteface toArray()来获取它的所有字段:
9q78igpj4#
这样完美地工作:)
2g32fytz5#
当我需要类似的东西时,我是这样做的(适用于问卷调查的例子):
参考文献: