Friday, March 11, 2022

[FIXED] cakephp 3 how to create new record from existing entity

Issue

I have an entity with related data and I want save it in new record.

I Try it:

$newTour = $this->Tours->get($id, ['contain' => ['Cities', 'Tags']]);
$newTour->set('id', null);
$this->Tours->save($newTour);

But I saw this error:

All primary key value(s) are needed for updating

what should I do?


Solution

Entities retrieved via get() or find() will be set as non-new, which causes them to end up in the update- instead of the insert-process when being saved.

If you want to insert them as new records, then you have to mark them as new, additionally to unsetting the primary key(s).

// ...
$newTour->isNew(true);
$newTour->unsetProperty('id');
// ...

See also



Answered By - ndm

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.