在 laravel 中与 "through" table 有一个关系

HasOne relationship in laravel with a "through" table

我目前的人际关系有问题。

我有 3 个 table:

每个派系都有很多角色,但每个角色只有一个派系。我已经考虑过在我的角色 table 中创建一个 faction_id 列,但我只想用 faction_roles 来解决它,所以我不必向 2 table 添加数据]s.

我的榜样是这样的:

 public function faction()
 {
    return $this->hasOne(Faction::class, 'faction_roles.faction_id', 'faction_roles.role_id');
 }

我已经用 $this->belongsTo(Faction::class) 试过了,但还是不行。

提前致谢!

干杯

如果您像在 Faction 模型中那样定义关系,我看不出问题所在:

public function factions() {
    return $this->belongsToMany(Faction::class);
}

然后关系方法是去return一个item,你可以这样查询关系的第一个元素:

$role->factions->first();

或者:

$role->factions()->first();

Eager loading for the difference

您还需要什么?