So I'm developing a system where a user can create a new account and upload a profile photo. I'm using two models: User for the account, Photo for the photos.
The users table has a foreign key on the field photoId that references to photos.id. The photos table has a userId field that has a foreign key referencing users.id. So there is a recursive relationship between User and Photo. Reason for this: when a Photo is created, we want to be able to see which User uploaded the Photo. A User has one Photo as his profile image.
So it's Photo hasOne User and User hasOne Photo. They are also configured this way in their Table classes.
Now, when a new User is saved, we want to also save a new Photo. Photo needs the id of the newly created User in order to save, but the User needs the id of the newly created Photo.
My question: what is the best method to save this? Should we allow User.photoId to be null, so that we can first save the User, then save the Photo, and then update the User with the correct Photo.id, or can CakePHP3 do some magic where it does all of this linking back and forth for you?
Data that comes from the form:
[
'username' => 'John Doe',
'mail' => '[email protected]',
'password' => 'whatever',
'photo' => [
'name' => 'myImage.jpg',
'type' => 'image/jpeg',
'tmp_name' => '/private/var/tmp/phpN3dVmL',
'error' => (int) 0,
'size' => (int) 40171
]
]
Yes! As long as your associations are setup correctly Cake will take care of the rest. So the best method is to pass your data array into
newEntityorpatchEntityand make sure that all passed fields are accessible in you entity.Saving hasOne relationships
Entities and mass assignment