I'm having trouble understanding the Eloquent relationships described here:
http://laravel.com/docs/4.2/eloquent#relationships
It says to use the hasOne()
method for a One-To-One relationship, which results in the following SQL:
select * from users where id = 1
select * from phones where user_id = 1
However, this looks like a One-To-Many relationship to me, since there may be more than one record in the phones
table with user_id = 1
.
The belongsTo()
method looks more like a One-To-One relationship, since their is a single foreign key that points to only a single record in another table.
I have a question on StackOverflow regarding this topic, and there is some more information/examples over there
I think I not quite understanding something here because to me, the hasOne()
and belongsTo()
are backwards.
Any insight is much appreciated.
They're just examples, hasOne describes exactly what it does - it returns ONE related object, and belongsTo is the inverse of the relationship. In the example, a User hasOne Phone and a Phone belongsTo a User.
If you wanted the user to have more than one phone, you would use hasMany which would then return an object collection (of Phones) when queried upon.
Take some time to learn basic php, a few months, then come back to laravel.
Also SQL. Learn some stored procedures, that will help you understand how to write a query.
The SQL generated by hasOne
is actually
select * from phones where user_id = 1 limit 1
The limit 1
ensures that only one record is returned.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community