【发布时间】:2018-04-09 10:51:03
【问题描述】:
首先让我为这个模糊的标题道歉,我找不到合适的方法来表述它。
至于问题,在这种情况下,我想将用户绑定到具有特定角色的项目。我正在尝试通过以下数据透视表执行此操作:
|user_has_projects|
|-----------------|
|id |
|user_id |
|projectrole_id |
|project_id |
|created_at |
|updated_at |
|deleted_at |
|-----------------|
users、projects 和 projectroles 表是您对上述表的期望。
目前每个模型的 Eloquent 关系如下:
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(...) 时,我收到以下错误:
“在布尔值上调用成员函数 projectRole()”..
经过一番彻底的搜索,我发现唯一返回的是
{"withTimestamps":true}
我在这里做错了什么?我找到了一些关于拥有多个模型的数据透视表的解决方案,但没有一个能以某种方式工作。
【问题讨论】:
标签: php laravel orm eloquent many-to-many