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

V4n*_*ll4 9 php laravel laravel-5 laravel-5.1

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

时间表

  • 用户身份

用户

  • ID

supervisor_user

  • 用户身份
  • 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();
}
Run Code Online (Sandbox Code Playgroud)

我想设置另一个关系,它将一个时间表列表"分配"给主管.我猜是hasManyThrough关系...但不完全是如何为它编写代码.

我怎样才能达到我的需要?

Nor*_*gul 6

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

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

在您的用户模型中创建一个方法:

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

然后拨打电话:

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

foreach($supervisorRole->users as $user)
    $timesheets = $user->timesheets;
endforeach
Run Code Online (Sandbox Code Playgroud)