2016-03-07 145 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()? –