2016-03-07 143 views
1

我试图让我认为是Laravel hasManyThrough与多个关键字段的关系。我的数据库是这样的:Laravel hasManyThrough与多个关键字段

  • 员工

    • ID
    • TEAM_ID>引用队
    • ID
    • teamleader1_user_id>引用员工
    • teamleader2_user_id>引用员工
    • teamleader3_user_id>引用员工

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

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

回答

0

您可以将它作为ManyToMany关系处理,并与三个OneToMany捆绑在一起。

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 Docs的Many to many

+0

好的,但是我如何通过所有的teamleader关系同时获取属于另一个员工的所有员工,例如Employee-> employees()? –