Support the ongoing development of Laravel.io →
posted 10 years ago
Eloquent

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.

Last updated 3 years ago.
0

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.

0

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.

0

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.

0

Sign in to participate in this thread!

Eventy

Your banner here too?

TrieBr triebr Joined 12 Jan 2015

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.