Let me start by apologizing for the vague title, I couldn't find a proper way to formulate it.
As for the question, in this instance I want to bind users to a project with a certain role. I'm trying to do this via the following pivot table:
|user_has_projects|
|-----------------|
|id |
|user_id |
|projectrole_id |
|project_id |
|created_at |
|updated_at |
|deleted_at |
|-----------------|
The users
, projects
and projectroles
tables are what you would expect from said tables.
The current Eloquent relationships per model are as follows:
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'
);
}
Now if I want to retrieve all the users bound to a project and then their roles in the project I would first call $aBoundUsers = $oProject->users();
and then loop through those users to get their roles with
foreach($aBoundUsers as $oUser) {
$role = $oUser->projectRole($oProject->id);
}
However, when I call $oUser->projectRole(...)
I get the following error: "Call to a member function projectRole() on boolean".. After some thorough searching I found out that the only thing returned is {"withTimestamps":true}
What am I doing wrong here? I found some solutions on having pivot tables with multiple models, but none work somehow.
$oProject->users()
only returns the relation, $oProject->users
returns the result.
Change the parent class of your UserProjects
model:
class UserProjects extends \Illuminate\Database\Eloquent\Relations\Pivot
Then adjust your Project
model:
public function users()
{
return $this->belongsToMany(
"App\User",
"user_has_projects"
)->withPivot(
"user_id", "projectrole_id"
)->using("App\UserProjects")
->withTimestamps();
}
Then you can access your roles like this:
foreach($oProject->users as $oUser) {
$role = $oUser->pivot->projectRoles;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments