2016-04-13 97 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->时间表

相关问题