0

I am implementing a query using Lighthouse.

I am using the @paginate directive, but it is a complex condition and I want to write it in a .php file.

I've looked and can't figure out how to do this, so I need help.

The following method failed to get the relation and resulted in null.

graphql - Laravel Lighthouse paginate field result - Stack Overflow Laravel Lighthouse paginate field result


Paginate Directive | Lighthouse https://lighthouse-php.com/3/api-reference/directives.html#paginate

isao
  • 3
  • 2
  • Share your `builder` class you've written. Common misconception is that it should return a paginator, but it should return an query. So returning `User::query()` from a `@paginator` builder class should yield the results you want (and you can make the query conditions as complex as you need). – Alex Sep 25 '22 at 09:11

2 Answers2

1

See this template.

Schema.graphql:

"Get a list of all cars."
    Cars(filter: carsFilter): [Car!]! @paginate(builder: "App\\GraphQL\\Queries\\Cars")

Cars.php:

public function __invoke($_, array $args, ?GraphQLContext $context, ResolveInfo $resolveInfo):Builder {

$carsQuery = Cars::query();

// Do whatever you want with your query.

/* @var QueryBuilder|EloquentBuilder|ScoutBuilder|Relation $carsQuery */
return $carsQuery;
}

Note that from your php class you must return a query builder instance NOT a collection.

mostafa
  • 196
  • 4
0

When you are using the builder argument in the paginate directive you are losing the mutators the model has. (because you are replacing the query builder with a custom builder).

Try to use scopes if it is possible. That way, you don't lose the mutators or castings you may have on your model.

Cars(filter: carsFilter): [Car!]! @paginate(scopes: ["myCondition", "mySecondCondition")

You can add scopes as functions in the model like:

public function scopeMyCondition(Builder $query): Builder
{
    return $query->where('color', '<>', 'red');
}

public function scopeMySecondCondition(Builder $query): Builder
{
    return $query->whereIn('mts', '>', 100);
}
faiverson
  • 21
  • 3