You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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);
    }
}

解决方案

  1. 创建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');
    }
}
  1. 更新GraphQL Schema中的查询定义
getProducts(orderBy: _ @orderBy): [Product!]!
    @all
    @builder(method: "App\GraphQL\Queries\ProductBuilder@getProducts")
  1. 执行带关联字段排序的查询
{
    getProducts(orderBy: {column: "categories.name", order: ASC}){
        id
        code
        article
        category {
            name
       }
   }
}

内容的提问来源于stack exchange,提问作者Agustin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 18:50:25