简体   繁体   中英

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

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.

You need to make new table, which might be called "mate".

mate

id

player_id (unique, not null)

player_id (unique, not null)

Then you pair them from Players table with belongsToMany().

Unique constraint says that a Player cant be in more than 1 pair.

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');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM