In my CakePHP 3 app, I have a somewhat elaborate tree of entities that I need to clone and save.
The root of the structure is a Questionnaire, a Questionnaire hasMany Questions, each Question hasMany Fields, etc. (it goes deeper). Now I want the user to be able to define a new questionnaire by copying an old one. Then they can change whatever they need.
I can get a dump of what I need to copy by using $questionnaire->$this->Questionnaires->get($id)
with the appropriate contain fields. Is there a clever way to save this as a bunch of new entities while preserving the data and the structure between them?
Advertisement
Answer
I think the best possible way would be following work flow:
- Get object you want to clone
- Go through the collection and remove all ID’s
- Convert to array and use that in
$this->Questionnaires->newEntity($arrayData, ['associated' => ['Questions', '...']]);
- Now save the new entity with all the related data you want to keep
AFAIK there’s no “smarter” way of cloning an entity with associations in Cake 3 🙂