如何在Laravel Lighthouse GraphQL中按关联字段排序?
Laravel Lighthouse GraphQL 按关联模型字段排序问题解决
问题场景
Product模型与Category模型为一对一关联(Product属于Category),但执行getProducts查询时无法按Category的字段进行排序。
现有代码
GraphQL Schema
getProducts(orderBy: _ @orderBy): [Product!]! @all type Product { id: ID code: String article: String category: Category } type Category { id: ID name: String products: [Product] }
Laravel 模型代码
class Product extends Model { ... public function category() { return $this->belongsTo(Category::class); } } class Category extends Model { ... public function products() { return $this->hasMany(Product::class); } }
解决方案
- 创建ProductBuilder类
<?php namespace App\GraphQL\Queries; use Illuminate\Database\Eloquent\Builder; class ProductBuilder { public function getProducts(Builder $builder) { return $builder->join('categories', 'categories.id', '=', 'products.category_id'); } }
- 更新GraphQL Schema中的查询定义
getProducts(orderBy: _ @orderBy): [Product!]! @all @builder(method: "App\GraphQL\Queries\ProductBuilder@getProducts")
- 执行带关联字段排序的查询
{ getProducts(orderBy: {column: "categories.name", order: ASC}){ id code article category { name } } }
内容的提问来源于stack exchange,提问作者Agustin
相关产品推荐
相关产品推荐

