Laravel拥有多个关键字段的ManyThrough


Laravel hasManyThrough with multiple key fields

我正在尝试使我认为是Laravel具有多个关键字段的ManyThrough关系。我的数据库如下所示:

  • 员工

    • 编号
    • team_id>参考资料
    • 团队
    • 名字
  • 团队

    • 编号
    • teamleader1_user_id>参考资料 员工
    • teamleader2_user_id>参考资料
    • 员工
    • teamleader3_user_id>参考资料 员工

我知道数据库设置不太理想,但由于它是一个外部应用程序数据库,我无法更改任何内容。

在我的员工模型中,我想创建一个关系,以便可以通过 Teams 中的团队负责人字段之一提取属于员工的所有员工。如何设置?

您可以将其处理为多对多关系,与三个一对一对多捆绑在一起。

class Team extends Model{
public function employees()
{
    return $this->hasMany('App'Employee');
}
public function teamleader1()
{
    return $this->hasOne('App'Employee','teamleader1_user_id');
}
public function teamleader2()
{
    return $this->hasOne('App'Employee','teamleader2_user_id');
}
public function teamleader3()
{
    return $this->hasOne('App'Employee','teamleader3_user_id');
}
}
class Employee extends Model {
    public function teams()
    {
        return $this->belongsToMany('App'Team');
    }
}

您可能有一个名为 employee_team 的中间表,其中包含该"name"属性。有关更多信息,您可以查看 Laravel 文档上的多对多关系。