laravel-5 - 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()
{
????
}
解决方案
您只需像添加其他关系一样添加它:
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);
我假设所有用户记录都有一个外键championships
表championship_id
当您调用$user->championship
关系时,它会将championship
wrt 返回到其外键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.
推荐阅读
- javascript - 在 nodejs 单元测试中使用 mocha 处理不同的响应
- c# - 在 MVC ASP.NET 应用程序中记录有关上传文件的信息 - “文件”看似为 NULL
- python - 来自站点的静态文件工作,但不是来自应用程序
- google-bigquery - Datastudio 和 BigQuery 分区列
- python - 使用 Pyspark 检查 IP 地址是否在 IPNetwork 中
- javascript - 如何使用函数构造 JavaScript for 循环
- typescript - WebStorm's TypeScript Lint: Callback Parameter Type
- python - Python - 如何在多个直方图上具有相同的最大值
- azure-active-directory - 是否可以将 $filters 与 msgraph /groups/delta 一起使用?
- javascript - 点击事件回调在用户第二次点击时被调用