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

Lighthouse中@belongsToMany与@paginate指令冲突导致分页失败问题

解决Lighthouse中@belongsToMany与@paginate的冲突问题

问题原因

@belongsToMany和@paginate都实现了Nuwave\Lighthouse\Support\Contracts\FieldResolver接口,Lighthouse不允许同一个字段绑定多个字段解析器类型的指令,因此触发冲突报错。

解决方案

移除@belongsToMany指令,改用@paginate的relation参数指定模型中的关联关系,同时调整返回类型为分页结果类型:

  1. 修改User类型的topics字段定义
type User {
    id: ID!
    uuid: String!
    email: String!
    api_token: String!
    devices: [Device]

    topics(
        orderBy: _ @orderBy(
            columns: ["created_at", "last_message_at"]
        )
    ): SimplePaginateResult! @paginate(type: SIMPLE, relation: "topics")

    created_at: DateTime!
    updated_at: DateTime!
}
  1. 添加SimplePaginate相关类型定义
    如果项目未自动引入Lighthouse的分页类型,需手动补充:
type SimplePaginateResult {
    data: [Topic!]!
    links: PageLinks!
    meta: SimplePaginateMeta!
}

type PageLinks {
    first: String!
    last: String!
    prev: String
    next: String
}

type SimplePaginateMeta {
    currentPage: Int!
    from: Int!
    lastPage: Int!
    perPage: Int!
    to: Int!
    total: Int!
}
  1. 调整查询结构
    由于topics现在返回分页包装对象,查询时需嵌套到data字段获取Topic数据:
{
  me {
    email
    topics {
      data {
        title
        last_message_at
      }
      # 可选:获取分页元信息
      meta {
        currentPage
        total
        perPage
      }
    }
  }
}

原理说明

@paginate指令支持通过relation参数直接关联模型中的关联方法(即User模型里的topics()关联方法),无需再用@belongsToMany指定关联关系,这样既实现了分页功能,又避免了解析器冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 17:42:40