2016-04-13 83 views
9

我在我的應用程序中設置了以下模型/表格;Laravel 5.1有許多關係和數據透視表

時間表

  • user_id說明

用戶

  • ID

supervisor_user

  • USER_ID
  • supervisor_id

用戶就可以通過該supervisor_user透視表 「分配」 給監督員。

我在User模型上有以下關係設置,它可以獲取管理員用戶。

/** 
* The supervisors that are assigned to the user. 
* 
* @return Object 
*/ 
public function supervisors() 
{ 
    return $this->belongsToMany('App\Models\User\User', 'supervisor_user', 'user_id', 'supervisor_id')->withTimestamps(); 
} 

我想建立另一種關係,獲得時間表「分配」給主管。我猜與hasManyThrough關係...但不完全如何編寫它的代碼。

我該如何實現我所需要的?

回答

6

在你的榜樣做的方法:

public function users() 
{ 
    return $this->belongsToMany('App\Models\User\User', 
      'supervisor_user', 'supervisor_id', 'user_id')->withTimestamps(); 
} 

在您的用戶模型做的方法:

public function timesheets() 
    { 
     return $this->hasMany('App\Timesheet', 'user_id'); 
    } 

然後撥打電話:

$supervisorRole = Role::find($id); 

foreach($supervisorRole->users as $user) 
    $timesheets = $user->timesheets; 
endforeach 
+0

嗨,感謝您的回覆。沒有'Supervisor'模型,因爲這個應用程序是基於角色的,我有一個'role'模型。我忘了在上面提到這一點。 – V4n1ll4

+0

然後像這樣^ – Norgul

+0

現在我得到這個錯誤:'未定義的屬性:Illuminate \ Database \ Eloquent \ Collection :: $ timesheets' – V4n1ll4

2

是的,你是正確的,你可以使用兩種方法爲主管實現時間表。使用連接查詢,即連接多個表並查找時間表或使用hasManyThrough。

簡單的方法:因爲您在supervisor表中擁有user_id,並且我認爲這是屬於給定主管的用戶。我們可以簡單地比較supervisor_users.user_id和timesheets.user_id。

$timesheets = db:table('timesheets') 
->join('supervisor_user','timesheets.user_id','=','supervisor_users.user_id')->get(); 

這應該是關鍵。如果您需要添加where或select子句,請在get()之前添加。

更快的方法: 如果您檢查laravel文檔,對於hasmanythrough,您可能會遇到一對多,一對多的情況。如此:國家有許多用戶,用戶有很多帖子。在這個,如果我們做了很多,我們可以拉出屬於國家的帖子。對你而言,我所看到的是,單個主管有許多用戶,用戶有很多時間表。如果我錯了,請在這裏更正我的解決方案,因此我會幫助您爲給定的主管獲取時間表。儘可能短的屬於用戶的所有時間表都屬於給定的主管。您將擁有給定主管的所有用戶的所有時間表。

public function timesheets() 
    { 
     return $this->hasManyThrough('App\SupervisorUser', 'App\User'); 
    } 

這裏的論點之一是你想要數據的最終表。第二個參數是我們經過的中間表。如果你喜歡Id的話,你可以添加第三和第四個參數。 現在簡單地嘗試: $ supervisor_timesheet = $ Supervisor_user->時間表

相關問題