I am playing around with Laravel and came across something in the documentation for defining 1 to 1 relationships between tables that I would like to get feedback on.
The example in the docs is between a user
table phone
table, where each user
can have one phone
entry.
Here is the Laravel example:
class User extends Eloquent {
public function phone()
{
return $this->hasOne('Phone');
}
}
If you get a single user with the ORM, the following query is run:
select * from users where id = 1
And if you try access the phone number in the result, the framework will see the relationship and run
select * from phones where user_id = 1
That's where my question comes up. I would have had a phone_id
column in the user
table schema, and the query to get the phone number would be:
select * from phones where id = [user.phone_id]
Thinking about it while typing the post, the 'Laravel' way seems to have the benefit of being able to become a 1 to many relationship, which got me wondering if I've been doing it wrong all this time?
How do you normally structure your schema for 1 to 1 and 1 to many relationships?
Best Answer
Since you didn't follow the convention of Eloquent you have to type it manually and it's easy just specify the second and third arguments into the
hasOne
or other functions of ORM obj.i.e:
Where the second argument is the column name of the first argument (the table you want to make relation with, in this case
Phone
) and the third argument is the column name in this modelUser