Reputation: 653
I have 2 tables liked in CakePHP app, one is Users which hasOne Profile liked to.
I have managed to automatically create entries in both when creating a new user, but, when I try to edit everything in my user-edit page, it will create a new profile entry, causing my user to have 2 profiles linked to.
Both models are perfectly coded and linked, as I said, I'm able to create a new user and the system automatically creates the profile and links it.
Here is my user_controller.php with the edit function that is not working properly:
function edit($id = null) { if (!$id && empty($this->data)) { $this->Session->setFlash(__('Invalid User', true)); $this->redirect(array('action' => 'index')); } if (!empty($this->data)) { if ($this->User->save($this->data)) { $this->data['Profile']['user_id'] = $this->User->id; $this->User->Profile->save($this->data); $this->Session->setFlash(__('User saved', true)); $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash(__('The user could not be saved. Please, try again.', true)); } } if (empty($this->data)) { $this->data = $this->User->read(null, $id); } }
Thanks a lot for the help!
Upvotes: 1
Views: 215
Reputation: 7853
Well, from what it appears by your code it is doing exactly what you're telling it to do. It is taking the user.id
and saving a new profile with it.
There's no condition set on $this->User->Profile->save()
by the looks of your code. You need to specify what profile to save the edits too. Otherwise Cake is gonna think you want to save a new one. So, if you have the Profile ID in a hidden form field it should look something like this
$this->User->Profile->save(
$this->data,
array(
'conditions' => array(
'Profile.id' => $this->data['Profile']['id']
)
)
);
Now you should be updating a specific profile instead of just saving a new one every time.
Let me know if it works or not.
Edit:
After giving it some thought it is very weird that you're even able to save two profiles with the same user ID. This should have failed at the database level, before it was even saved. I would recommend setting up a unique index on profiles.user_id
as well to ensure you don't run into problems in the future where a user has multiple profiles.
(Unless it was intended behavior to have multiple profiles with the same user in which case ignore the edit!)
Upvotes: 1