laravel-graphql
laravel-graphql copied to clipboard
How to use relations with GraphQL?
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.
Why don't you add it as a field, in the Type, add a field like name, email, just add roles.
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;
});
},
],
Is there a way to return a key ?
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.