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

How to use relations with GraphQL?

Open shabaz-ejaz opened this issue 7 years ago • 4 comments

Lets say I have a many to many relation. Users can have many Roles.

I have the relational structure:

users ----- user_roles ----- roles

If I have a UserQuery in GraphQL how would I automatically pull in all of the roles if the arg is set?

For example if the query is something like: graphql/users?query=query+FetchUsers{users{id,email,roles}}

Here is the UsersQuery resolve method:

public function resolve($root, $args)
    {

        $user = new User;

        // check for limit
        if( isset($args['first']) ) {
            $user =  $user->limit($args['first'])->latest();
        }

        if( isset($args['offset']) ) {
            $user =  $user->offset($args['offset']);
        }

        if(isset($args['email']))
        {
            $user = $user->where('email', $args['email']);
        }

        if(isset($args['id']))
        {
            $user = $user->where('id' , $args['id']);
        }

        return $user->get();
    }

How can I fetch the roles from the relation here? I already have my model relationships set up as a many to many.

shabaz-ejaz avatar Feb 23 '18 12:02 shabaz-ejaz

Why don't you add it as a field, in the Type, add a field like name, email, just add roles.

kikoseijo avatar Feb 23 '18 18:02 kikoseijo

Yes you can, like @kikoseijo has mentioned you should add that to your Type.

You could do something like this:

'roles' => [
    'type' => Type::listOf(Type::string()),
    'description' => 'All role names that belongs to this user',
    'resolve' => function (User $user) {
        return $user->roles->map(function ($role) {
            return $role->name;
        });
    },
],

kevinvdburgt avatar Mar 04 '18 20:03 kevinvdburgt

Is there a way to return a key ?

levilucas03 avatar Aug 20 '18 11:08 levilucas03

Is there a way to return a key ?

If you mean generally, then no: GraphQL (by it's spec) does not support Map types (i.e. arbitrary key=>value) references.

"Keys" in the sense can only be typed fields.

mfn avatar Aug 20 '18 11:08 mfn