laravel-graphql
laravel-graphql copied to clipboard
How do I get "pivot" information on a many to many relation object?
Lets say I have a many to many relation. Users
have many Groups
.
The relation structur is: user --- user_group -- group
From the table user_group
I need the additional information role_id. This usually looks like this:
{
"id": 1,
"name": "Name",
...
"pivot": {
"user_id": 3,
"group_id": 1,
"role_id": 5
}
},
UserType.php
public function fields()
{
return [
'id' => [
'type' => Type::nonNull(Type::ID()),
'description' => 'The id of the user'
],
...
'groups' => [
'type' => Type::listOf(GraphQL::type('Group')),
'description' => 'The user groups',
],
];
}
GroupTyp.php
public function fields()
{
return [
'id' => [
'type' => Type::nonNull(Type::ID()),
'description' => 'The id of the group'
],
'name' => [
'type' => Type::string(),
'description' => 'The name of the group'
]
....
],
'pivot' => [
'type' => Type::listOf(Type::string()),
'description' => 'The relation details'
],
];
}
In this case, I get the answer null.
How do I get the information from the "pivot" area?
Try something like this:
'pivot' => [
'type' => Type::listOf(GraphQL::type('User')),
'description' => 'The relation details',
'resolve' => function (Group $group) {
return $group->users;
},
],
Many thanks for your response!
But I need the role_id
from intermediate table and not a list of the relatet group users.
Did you solve it?
I had the same problem. The solution is to define the role_id as a field in your GroupTyp.php with a resolve function
'role_id' => [
'type' => Type::int(),
'description' => 'role id'
'resolve' => function(Group $group) {
return $group->pivot->role_id;
}
],