V
V
Vasya902021-02-03 13:12:51
Laravel
Vasya90, 2021-02-03 13:12:51

What is the difference between belongsTo and hasOne relationships?

Can someone explain in simple terms what is the difference between them. Without parcels to Google and documentation.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jazzus, 2021-02-03
@Vasya90

Laravel will tell you the difference if you do not prescribe keywords. You can write incorrect keywords in the hasOne/belongsTo relationship and everything will work. But the relationship will be drawn incorrectly.
There are 2 differences.
Technical
When user hasOne/hasMany phones Laravel expects this model id (User) to be equal to user_id in Phone
When phone belongsTo user Laravel expects this user_id of model (Phone) to be equal to model id in
User its id is in the Phone model, but the phone_id is not in the User model. Therefore User hasOne Phone and Phone belongsTo User.
Logical
Correct: The user has one phone. The user has many phones. The phone belongs to the user.
The fact that the phone has a user is now common, but logically incorrect)
Briefly speaking. In user we prescribe hasOne phone / hasMany phones. In Phone belongsTo user.

S
Sergey delphinpro, 2021-02-03
@delphinpro

hasOne - a one-to-one relationship
example: the user has only one phone and the phone has one owner (user)
belongsTo - this is a one-to-many return
Example: the user has several phones, but each phone has one owner.
This means that the relation in the User model will be hasMany, and in Phone - belongsTo

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question