15

For the case of a one-to-one relationship, if I fully specify the keys in the method calls, is there a difference between hasOne and belongsTo relationships? Or, asked differently, if I used hasOne on both sides of the relation, would it be the same result?

1
  • Sorry, this is not an answer. You only stated a conclusion. Pay attention to the detail: "if I fully specify the keys", i.e. the optional arguments to hasOne() and belongsTo(). Oct 2, 2014 at 15:45

1 Answer 1

12

Yes it works for some cases to specify the keys and make the relation work. And with some cases I mean mainly retrieving results. Here's an example:

DB

users                profiles
-----                --------
id                   id
etc...               user_id
                     etc...

Models

Using "wrong" relations with hasOne twice

class User extends Eloquent {
    public function profile(){
        return $this->hasOne('Profile');
    }
}

class Profile extends Eloquent {
    public function user(){
        return $this->hasOne('User', 'id', 'user_id');
    }
}

Queries

Let's say we wanted to get the user from a certain profile

$profile = Profile::find(1);
$user = $profile->user;

This is working. But it's not working how it's supposed to be. It will treat the primary key of users like a foreign key that references user_id in profiles.

And while this may work you will get in trouble when using more complicated relationship methods.

For example associate:

$user = User::find(1);
$profile = Profile::find(2);
$profile->user()->associate($user);
$profile->save();

The call will throw an exception because HasOne doesn't have the method associate. (BelongsTo has it)

Conclusion

Whereas belongsTo and hasOne may behave similar in some situations. They are clearly not. More complex interactions with the relationship won't work and it's nonsense from a semantic point of view.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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