0
votes

EDIT, I am rewriting the question for more clarity.

I have a "profile" model that has a belongs to relationship to a "user" model.

A certain user exists already. Later he creates a profile. The profile controller takes care of creating a new entry, but then needs to update a profile_id field as part of the associated user. I was under the impression that saveAll could take care of all the associations but it is not working?

What is the easiest/CakePHP standard way to do something like this? Thanks!

2
your question is not very clear. What are you trying to do? - Anh Pham
after creating, via save(), a model, i want to immediately save a property of an associated model - PCC
yeah, you can do that, you just need the id of the record you want to modify. - Anh Pham
apologies, i know the question was worded badly. rewrote the entire thing for (hopefully) more clarity - PCC

2 Answers

1
votes

saveAll() creates new records. So you can't use it to update an already existing record in the Users table. As Anh Pham already mentioned, you've got your associations wrong. A Profile belongs to a User, and a User has one Profile. By having a profile_id field in your Users table, you're doing it the other way around.

So remove the profile_id field from the Users table, add a user_id field to the Profiles table, and update your model associations in user.php & profile.php.

To save a new Profile for an existing User, you can then either query the user id for the current User, or for example retrieve it through Auth, and add it manually to $this->data prior to calling the save() method of your Profile method.

1
votes

You shouldn't have a profile_id field in the users table, you should have user_id field in profile table (the foreign key is similar to hasMany relationship). I'm surprised that the app still works http://book.cakephp.org/view/1041/hasOne

Also, I usually don't have hasOne relationship. If User hasOne Profile, then just include all fields in the profiles table into users table, unless there's some reason not to do it. But again, it's just my preference.