If I have the following table (and corresponding Eloquent Relationships)
posts:
| id | user_id | content |
|----|---------|---------|
| 1 | 1 | foo |
| 2 | 2 | bar |
| 3 | 2 | foobar |
| 4 | 1 | asd |
| 5 | 1 | asdf |
How should I construct the 'posts' field in UserType so when I make this query
{
users {
id
posts(limit: 2) {
id
}
}
}
I get
{
"data": {
"users": [
{
"id": 1,
"posts": [
{
"id": 5
},
{
"id": 4
}
]
},
{
"id": 2,
"posts": [
{
"id": 3
},
{
"id": 2
}
]
}
]
}
}
(the list is paginated by 2 elements and ordering by descending id)
Have you looked at https://github.com/rebing/graphql-laravel#type-relationship-query?
In your case, you could so something like:
class UserType extends GraphQLType
{
// ...
public function fields(): array
{
return [
// ...
// Relation
'posts' => [
'type' => Type::listOf(GraphQL::type('post')),
'description' => 'A list of posts written by the user',
'args' => [
'limit' => [
'type' => Type::int(),
],
],
'query' => function(array $args, $query, $ctx) {
return $query->limit($args['limit']);
}
]
];
}
}
@georgeboot Thank you for answering. I did look into the documentation first but couldn't get it to work. I tried your code in a test project, but the query returns the full list of post of each user, because it is ignoring the "query" field. I even put a line to throw an exception and it did nothing. Is there anything else I should configure to execute that query?
Can you share your code somewhere? Think there might be another issue somewhere.
TestFiles.zip
I attached the files I modified in my test and an SQL with the DB data if you want it. I don't know if there is a better way to share my code, but this should do the job. Let me know if you need anything else. Thank you for helping me.
I solved my problem. As @georgeboot said, the problem was somewhere else in the code, specifically in UserQuery.php. The resolve function should be something like:
public function resolve($root, $args, $context, ResolveInfo $resolveInfo, Closure $getSelectFields)
{
$fields = $getSelectFields();
$select = $fields->getSelect();
$with = $fields->getRelations();
return User::select($select)->with($with)->get();
}
Now I have a the problem that the limit is aplied to all queried posts, not for each user, but that's related to #442 so I close this issue. Thank you George.
Most helpful comment
I solved my problem. As @georgeboot said, the problem was somewhere else in the code, specifically in
UserQuery.php. Theresolvefunction should be something like:Now I have a the problem that the limit is aplied to all queried posts, not for each user, but that's related to #442 so I close this issue. Thank you George.