首页 > 解决方案 > Laravel如何用一个模型定义3个关系?

问题描述

我有一个模型,叫做冠军。锦标赛可能有3名裁判,分别称为主裁判、主秘书和裁判操作员。

所有这些都链接到用户模型并作为用户 ID 存储在数据库中。

我的人际关系看起来像这样

class Championship extends Model
{
    protected $table = 'championships';

    public function mainJudge()
    {
        return $this->hasOne('App\User', 'id', 'main_judge');
    }

    public function mainSecretary()
    {
        return $this->hasOne('App\User', 'id', 'main_secretary');
    }

    public function judgeOperator()
    {
        return $this->hasOne('App\User', 'id','judge_operator');
    }
}

但我无法理解如何在用户模型中定义反向关系

class User extends Authenticatable
{
    public function sex()
    {
        return $this->belongsTo('App\Models\Sex');
    }

    public function player()
    {
        return $this->hasOne('App\Models\Player', 'user_id');
    }

    public function championship()
    {
    ????
    }

标签: laravel-5eloquent

解决方案


您只需像添加其他关系一样添加它:

public function championship()
{
   return $this->belongsTo('App\Championship');
}

当你这样做:

$championship = Championship::find($id);
$mainJudge = $championship->mainJudge;
$mainSecretary = $championship->mainSecretary;

// All objects will be exactly same
dd($mainJudge->championship,$mainSecretary->championship,$championship); 

我假设所有用户记录都有一个外键championshipschampionship_id

当您调用$user->championship关系时,它会将championshipwrt 返回到其外键championship_id

不用担心你只是混淆了逆关系:

这样看:

Your mainJudge, mainSecretary, judgeOperators are of type App\User and every user have a championship_id when you will call the (App\User)->championship it will always return you its respective championship or null if the championship_id is empty. Its just matter of perspective.

Just try the above code it will clear out your confusion.


推荐阅读