能否在不查询模型数据时使用Lighthouse-PHP的@paginate指令?
非模型场景下使用Lighthouse PHP的@paginate指令完全可行
默认情况下,Lighthouse的@paginate指令绑定Eloquent模型,但你可以通过自定义指令解析器适配第三方API或其他非模型数据源的分页需求。
具体实现步骤:
自定义分页指令类
新建指令类,实现Nuwave\Lighthouse\Schema\Directives\PaginateDirectiveInterface,或直接继承Nuwave\Lighthouse\Schema\Directives\PaginateDirective并重写resolve方法。在方法内处理第三方API请求,手动构建符合Laravel规范的分页实例。示例代码:
<?php namespace App\GraphQL\Directives; use Nuwave\Lighthouse\Schema\Directives\PaginateDirective; use Illuminate\Pagination\LengthAwarePaginator; use GraphQL\Type\Definition\ResolveInfo; use Illuminate\Support\Facades\Http; class CustomPaginateDirective extends PaginateDirective { public function resolve($root, array $args, $context, ResolveInfo $resolveInfo) { // 提取GraphQL传入的分页参数 $page = $args['page'] ?? 1; $perPage = $args['perPage'] ?? 15; // 请求第三方API并携带分页参数 $apiResponse = Http::get('https://third-party-api.com/data', [ 'page' => $page, 'per_page' => $perPage, ])->json(); // 从API返回结果中提取数据和总条数 $items = $apiResponse['data']; $total = $apiResponse['meta']['total']; // 构建Laravel分页实例,适配Lighthouse的返回格式 return new LengthAwarePaginator( $items, $total, $perPage, $page, ['path' => request()->url()] ); } }在GraphQL Schema中注册并使用自定义指令
在schema文件中注册指令,然后在需要分页的字段上调用:directive @customPaginate on FIELD_DEFINITION type Query { thirdPartyData: [ThirdPartyDataType!]! @customPaginate } type ThirdPartyDataType { id: ID! name: String! # 其他业务字段... }配置指令映射(可选,自动发现模式可跳过)
在config/lighthouse.php的directives数组中添加类映射:'directives' => [ 'customPaginate' => App\GraphQL\Directives\CustomPaginateDirective::class, ],
完成上述配置后,该字段会像原生@paginate一样返回包含data和paginatorInfo的标准分页结构,完美适配第三方API场景。
内容的提问来源于stack exchange,提问作者joh3rd
相关产品推荐
相关产品推荐

