1

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?

  • A one-to-one relationship is just a special case of one-to-many, where there exists only a single record on the many side for each ID on the one side. In other words, a 1 to many can easily degrade to a 1 to 1 by adding an additional constraint. – Robert Harvey Jan 16 '15 at 22:27
  • Im not sure exactly what the question is. How do we structure things in the database or in Laravel models? Eloquent tries to make things "make sense" so if you have a user that has one and only one phone number then you use a hasOne relationship. If users can have more than one phone number you use the hasMany relationship. you COULD reverse it but does it make as much sense to say "This phone number has one user or many users." While technically you COULD do this and it would work its not as logical for a phone number to own a user. – Bill Garrison Mar 17 '15 at 15:59
2

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:

class User extends Eloquent {
   public function phone()
   {
      return $this->hasOne('Phone','id','phone_id');
   }

}

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 model User

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.