This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the databases category.
Last Updated: 2024-11-21
The only difference between hasOne
and belongsTo
is where the foreign key
column is located.
Let's say you have two entities: User and an Account.
If the users table has the account_id
column then a User belongsTo
Account. (And the Account either hasOne
or hasMany
Users)
But if the users table does not have the account_id
column, and instead
the accounts table has the user_id
column, then User hasOne
or hasMany
Accounts
In short hasOne
and belongsTo
are inverses of one another - if one record
belongTo
the other, the other hasOne
of the first. Or, more accurately,
eiterh hasOne
or hasMany
- depending on how many times its id appears.