Laravel 5.1具有ManyThrough关系和数据透视表


Laravel 5.1 hasManyThrough relationships and pivot table

我在应用程序中设置了以下模型/表;

时间表

  • 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关系。。。但不完全是如何为其编写代码。

我怎样才能实现我需要的?

在您的角色模型中创建一个方法:

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

是的,您是对的,您可以使用两种方法为主管实现时间表。要么使用联接查询,即联接多个表并查找时间表,要么使用hasManyThrough。

简单的方法:因为您在supervisor表中有user_id,我假设它是属于给定supervisor的用户。我们可以简单地将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->时间表