3

I'm a bit confused in how CakePHP does it's database relationship.

For a hasOne relationship, according to the documentation:

"User hasOne Profile"

User hasOne Profile -> profiles.user_id

Array
(
    [User] => Array
        (
            [id] => 121
            [name] => Gwoo the Kungwoo
            [created] => 2007-05-01 10:31:01
        )
    [Profile] => Array
        (
            [id] => 12
            [user_id] => 121
            [skill] => Baking Cakes
            [created] => 2007-05-01 10:31:01
        )
)

But isn't this a one to many relation?

For example (I made these table to illustrate my confusion):

enter image description here

enter image description here

In this case then there are 2 profiles belonging to the same user. Doesn't this mean a user hasMany profile?

Would it make more sense if "User hasOne Profile" is

enter image description here

enter image description here

So then this would be "User hasOne Profile" but "Profile hasMany User"?

I'm not sure if I'm understanding this correctly.

Timber
  • 859
  • 9
  • 25

1 Answers1

2

In the example at the documentation when its said that a user has one profile it means that a user can only have one profile.

Therefor is a one to one relationship. You can choose where you prefer to have the foreign key, and they preferred to use it on the profile table.

Your images are wrong. In your case it would be a one to many. Which is a hasMany + belongsTo. They just decided that there will be only one profile per user, if you want to have many profiles per user, then it won't be a hasOne. That's your decision.

Alvaro
  • 40,778
  • 30
  • 164
  • 336
  • Okay, so if i'm understanding this correctly, the foreign that is placed on the `profile` table is unique then? – Timber Jul 25 '13 at 15:32
  • Yeah, that's it. By Design. – Alvaro Jul 25 '13 at 15:35
  • Ahh okay, I feel stupid now... So if you placed the `public $hasOne = 'Profile';` on the User model this will make the foreign key unique? else if you put `$hasMany` then it would allow duplicate entries. Is this correct? – Timber Jul 25 '13 at 15:37
  • I'm not sure about it. You can try it by yourself. You can otherwise add the restriction in the table and that will generate an error. – Alvaro Jul 25 '13 at 15:39
  • Sorry it took so long to mark this as the answer. I making my own tests. I was over thinking it. Your answer and comments helped a lot, so thank you :). – Timber Jul 26 '13 at 11:59