laravel-graphql icon indicating copy to clipboard operation
laravel-graphql copied to clipboard

How do I get "pivot" information on a many to many relation object?

Open tobiaskoennecke opened this issue 6 years ago • 4 comments

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?

tobiaskoennecke avatar Mar 26 '18 10:03 tobiaskoennecke

Try something like this:

'pivot' => [
    'type' => Type::listOf(GraphQL::type('User')),
    'description' => 'The relation details',
    'resolve' => function (Group $group) {
        return $group->users;
    },
],

kevinvdburgt avatar Mar 26 '18 12:03 kevinvdburgt

Many thanks for your response!

But I need the role_id from intermediate table and not a list of the relatet group users.

tobiaskoennecke avatar Mar 26 '18 13:03 tobiaskoennecke

Did you solve it?

EdnaldoNeimeg avatar Jul 16 '18 18:07 EdnaldoNeimeg

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;
              }
         ],

adhn avatar Jul 19 '18 12:07 adhn