Laravel如何groupBy嵌套关系



我有4个模型:User:用户模型

class User extends Authenticatable
{  
public function affectation()
{
return $this->hasMany(Affectation::class);
}
}

角色:榜样

class Role extends Model
{
public function operations()
{
return $this->hasMany(Operation::class);
}

public function affectation()
{
return $this->hasMany(Affectation::class);
}
}

Project:项目模型

class Project extends Model
{
public function affectation()
{
return $this->hasMany(Affectation::class);
}
}

Affectation:一个角色的用户对一个项目的Affectation(一个用户在同一个项目中可以有多个角色)

class Affectation extends Model
{
public function project()
{
return $this->belongsTo(Project::class);
}
public function role()
{
return $this->belongsTo(Role::class);
}
public function agent()
{
return $this->belongsTo(User::class, 'user_id');
}
}

我想在一个特定的项目中找到用户角色,我尝试了(对于id为1的项目):

return  User::whereHas('affectation', function (Builder $query) {
$query->where('project_id', '=', 1);
})->with('affectation.role')->get();

结果:

[
{
"id": 4,
"name": "Doe"
"affectation": [
{
"id": 1,
"role_id": 1,
"user_id": 4,
"project_id": 1
"role": {
"id": 1,
"name": "Dev"
}
},
{
"id": 2,
"role_id": 2,
"user_id": 4,
"project_id": 1
"role": {
"id": 2,
"name": "Scrum Master"
}
}
]
},
{
"id": 5,
"name": "Jhon"
"affectation": [
{
"id": 3,
"role_id": 1,
"user_id": 5,
"project_id": 1
"role": {
"id": 1,
"name": "DEV"
}
}
]
}
]

但我想这样实现:

[
{
"id":1,
"project_name":"Microsoft",
"users":[
{
"id":"1",
"name":"Doe",
"role":[
{
"id":"1",
"name":"DEV"
},
{
"id":"2",
"name":"SCRUM MASTER"
}
]
}
]
}
]

尝试在项目模型中添加:

/**
* Get all of the user for the project.
*/
public function users()
{
return $this->hasManyThrough(User::class, Affectation::class);
}

并将此添加到User model:

public function roles()
{
return $this->hasManyThrough(Role::class, Affectation::class);
}

传递给hasManyThrough方法的第一个参数是我们希望访问的最终模型的名称,而第二个参数是中间模型的名称。欲了解更多信息,请参阅官方文档:https://laravel.com/docs/8.x/eloquent-relationships#has-many-through

最后的查询应该如下所示:

return Project::where('id', '=', 1)->with('users.roles')->get();

最新更新