after reading the cookbook and various Q&A here I am still a bit confused conceptually about the model associations and what they do. And I was hoping that somebody can help me straighten this out. So here goes my question(s):
As far as I can understand model associations helps reading / finding associated data. So if I load a User then all Posts for that User will be loaded as well? But is it true that CakePHP doesn’t do much for saving new entries? For example: If I create a new Post then I have to specify the user_id field for the relevant User manually, CakePHP doesn’t do it automatically somehow? With manually I mean defining the mentor_id explicitly in this answer: CakePHP model associations table w/data and new table
And why is it necessary to “mention” both models when saving? $this->Mentor->Student->save($student) in example. Is it a way to keep track of two-way associations??
Yes, CakePHP will load all the associated data unless you unbind or bind the models or change the recursive property on the model you’re using.
You have to specify the ID for the user and then do save, when you save from the model with the specified ID it will handle the rest. For instance let’s say you have a Post and a User model, and the user is logged in using Auth:
So it’s not really neccessary to mention both models, in the case that you mention both you can do the following, again with Posts and Users as example.
This would be equivalent to the previous case, since you are loading the User model with the user data and saving a Post for that User.