Laravel Eloquent:通过具有多种关系的枢轴将表绑定到另一个表

时间:2018-04-09 10:51:03

标签: php laravel orm eloquent many-to-many

首先让我为模糊的标题道歉,我无法找到适当的方法来制定它。

至于问题,在这个例子中,我想将用户绑定到具有特定角色的项目。我试图通过以下数据透视表执行此操作:

|user_has_projects|
|-----------------|
|id               |
|user_id          |
|projectrole_id   |
|project_id       |
|created_at       |
|updated_at       |
|deleted_at       |
|-----------------|

usersprojectsprojectroles表格是您对表格的期望。

每个模型的当前雄辩关系如下:

Project.php

public function users()
 {
   return $this->belongsToMany(
      "App\User",
      "user_has_projects"
   )->withPivot(
      "user_id"
   )->withTimestamps();
}

public function userProjects()
{
    return $this->hasMany(
        "App\UserProjects",
        "project_id",
        "id"
    );
}

Users.php

public function projects()
 {
   return $this->belongsToMany(
      'App\Project',
      'user_has_projects'
   )->withPivot(
      'project_id'
   );
}

public function projectRole($id)
{
    return $this->belongsToMany(
        "App\ProjectRole",
        "user_has_projects"
    )->withPivot(
        "projectrole_id"
    )->wherePivot(
        "project_id",
        '=',
        $id
    );
}

ProjectRole.php

public function user()
{
    return $this->belongsToMany(
        "App\User",
        "user_has_projects"
    )->withPivot(
        "user_id"
    )->withTimestamps();
}

public function projects()
{
    return $this->belongsToMany(
        "App\Project",
        "user_has_projects"
    )->withPivot(
        "project_id"
    )->withTimestamps();
}

UserProjects.php

public function projectRoles()
{
    return $this->belongsTo(
        'App\ProjectRoles'
    );
}

public function users()
{
    return $this->belongsTo(
        'App\User'
    );
}

public function projects()
{
    return $this->belongsTo(
        'App\Project'
    );
}

现在,如果我想要检索绑定到项目的所有用户,然后检查他们在项目中的角色,我将首先调用 $aBoundUsers = $oProject->users(); 然后循环遍历这些用户以获得

的角色
foreach($aBoundUsers as $oUser) {
$role = $oUser->projectRole($oProject->id); 
}

然而,当我致电$oUser->projectRole(...)时,我收到以下错误: "在boolean"上调用成员函数projectRole(); 经过一番彻底的搜索,我发现唯一返回的是 {"withTimestamps":true}

我在这里做错了什么?我找到了一些有多个模型的数据透视表的解决方案,但没有一种工作方式。

1 个答案:

答案 0 :(得分:0)

$oProject->users()仅返回关系,$oProject->users返回结果。

更改UserProjects模型的父类:

class UserProjects extends \Illuminate\Database\Eloquent\Relations\Pivot

然后调整您的Project型号:

public function users()
{
    return $this->belongsToMany(
        "App\User",
        "user_has_projects"
    )->withPivot(
        "user_id", "projectrole_id"
    )->using("App\UserProjects")
    ->withTimestamps();
}

然后你可以像这样访问你的角色:

foreach($oProject->users as $oUser) {
    $role = $oUser->pivot->projectRoles; 
}