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
- Cookbook > Database Access & ORM > Saving Data > Saving Entities
- Cookbook > Database Access & ORM > Saving Data > Updating Data
- API > \Cake\Datasource\EntityTrait::isNew()
Answered By - ndm
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.