Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent: How to define a one-to-one relationship on the same model

Say I have a Tennis players model, and each player has a mate they're tied to for doubles games. How would I define that relationship in Eloquent? I'm used to the usual scenario in the docs (and have seen the same in many codebases) where the one-to-one relationship points to an entry in another table which makes it straight-forward where to put hasOne() and belongsTo().

A player can only have one mate plus no two players share the same mate, and their relationship is determined by the value in a mate_id field. So ideally I'd want to do $player->mate to get the mate.

So what goes in the mate() method that I'll add on the Player model, to satisfy the requirement of a hasOne() and belongsTo() as shown in the docs? Thanks

like image 948
Sam Avatar asked Dec 01 '25 20:12

Sam


2 Answers

Wouldn't hasOne relation work here?

Try this in your model

public function mate()
{
        return $this->hasOne('Player', 'mate_id');
}

I don't think we would need the reverse relationship, as doing $player->mate() on any one player will give the other.

like image 158
codisfy Avatar answered Dec 04 '25 09:12

codisfy


The one-to-one as I want it works when I define only the belongsTo(), it won't work if I use hasOne() as in the other answers.

public function mate()
{
    return $this->belongsTo('App\Player', 'mate_id');
}
like image 36
Sam Avatar answered Dec 04 '25 09:12

Sam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!