I was working with my User model in my Users controller. I wanted to store the profile_id inside of the users table. It should’ve worked like this.
- Save a user in the users table: $this->User->save($this->data);
- Save a profile in the profiles table: $this->User->Profile->($this->data);
- Update the same user in the user table with the just made profile id.
And of course this is where things get complicated. CakePHP didn’t want to save my data. Here’s the code.
if ( $this->User->save($this->data) ) { $this->User->Profile->save($this->data); $this->User->save( array("User" => array("profile_id" => $this->User->Profile->id) ) ; }
It felt to me as if CakePHP’s save() method wasn’t working right. It is supposed to decided to insert or update a record based on weather an primary key is present. It should be present if save($this->data) is called, it should set the id. But it didn’t and nobody knows why!
So what to do? I used $this->User->saveField() instead. Here’s the new code.
if ( $this->User->save($this->data) ) { $this->User->Profile->save($this->data); $this->User->saveField("profile_id", $this->User->Profile->id); }
Why couldn’t CakePHP do what it’s documentation said it could do? What was I doing wrong? In any case, after fixing this I changed the way my models work so that I no longer need to update the user table at all.
you need to set the id of the model so that cake can save the field to the right entry in the database.
i.e. quote from :
http://book.cakephp.org/view/75/Saving-Your-Data
Set the ID of the model ($this->ModelName->id = $id) just before calling saveField().
When you run a $this->Model->save() the ID from the inserted row should already be in $this->Model->id which means setting $this->Model->id with [another query here] is strange to me. Of course, I could totally be misunderstanding it too.
I don’t think you misunderstood that, that’s confusing for me too. Anyway “$this->ModelName->id = $id” was the solution for my UpdatePassword-Action too. Thank you!