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
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.
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');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With