简体   繁体   English

Laravel Lighthouse 如何在.php 文件中使用@paginate 指令?

[英]Laravel Lighthouse How to use @paginate directive with .php file?

I am implementing a query using Lighthouse.我正在使用 Lighthouse 实现查询。

I am using the @paginate directive, but it is a complex condition and I want to write it in a.php file.我正在使用 @paginate 指令,但它是一个复杂的条件,我想将它写在 a.php 文件中。

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.以下方法获取关系失败,结果为null。

graphql - Laravel Lighthouse paginate field result - Stack Overflow Laravel Lighthouse paginate field result graphql - Laravel 灯塔分页字段结果 - 堆栈溢出Laravel 灯塔分页字段结果


Paginate Directive |分页指令 | Lighthouse https://lighthouse-php.com/3/api-reference/directives.html#paginate灯塔https://lighthouse-php.com/3/api-reference/directives.html#paginate

I write the template here.我在这里写模板。

Schema.graphql: Schema.graphql:

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

Cars.php:汽车.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.请注意,从您的 php class 中,您必须返回查询生成器实例而不是集合。

When you are using the builder argument in the paginate directive you are losing the mutators the model has.当您在 paginate 指令中使用 builder 参数时,您将丢失 model 具有的突变器。 (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.这样,您就不会丢失 model 上可能拥有的突变器或转换。

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

You can add scopes as functions in the model like:您可以在 model 中将作用域添加为函数,例如:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM