PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, March 11, 2022

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

 March 11, 2022     cakephp, cakephp-3.0     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing