Saving with HABTM in CakePHP
-
05-07-2019 - |
Question
I am creating multiple associations in one go and there are a few problems when it comes to saving.
I have the following code:
<?php
foreach($userData as $user) {
$data = array('User' => array('id' => $user['id']), 'Site' => array('id' => $user['site_id']));
$this->User->save($data);
}
?>
I have experimented with formatting the data array in different ways although I always encounter the same problems. Either the previous entries get moved when a new one is inserted or the current one gets updated.
I could just use the following although I need a behavior to trigger.
$this->User->SiteUser->save($data);
Edit: Also $this->User->create(); doesn't seem to do much.
Solution
The IRC helped work out what was wrong, once the unique key was set to false everything was able to save correctly.
//In the user model
var $hasAndBelongsToMany = array(
'Site' => array(
'className' => 'Site',
'unique' => false
)
);
OTHER TIPS
Try resetting the id
before a new save()
, possibly on both models:
$this->User->id = null;
Cake decides whether to update or insert entries based on the set id
, and save()
sets an id
automatically. Not sure why create()
doesn't take care of this for you.
Also, if you want to save HABTM data, you should need to use saveAll()
instead of save()
. Also see this question.