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

Laravel Lighthouse中如何让graphql-codegen生成正确类型定义?

解决graphql-codegen与Laravel Lighthouse schema不匹配问题

核心问题

你使用了Lighthouse的@paginate指令,这个指令会自动把posts字段的返回类型从[Post!]!转换成包含data、meta、links的分页结果类型,但你的本地schema.graphql仅定义了原始数组类型,未包含分页相关的类型定义,导致codegen校验查询时,发现查询中的posts.data在本地schema中不存在,从而报错。


方案一:从Lighthouse GraphQL端点拉取真实schema(推荐)

修改codegen.yml的schema配置,直接指向你的Laravel应用的GraphQL端点,替代本地schema文件:

overwrite: true
schema: "http://your-laravel-app.test/graphql" # 替换为你的实际GraphQL服务地址
documents: "./resources/js/pages/**/*.vue"
generates:
  ./resources/js/generated.ts:
    plugins:
      - "typescript"
      - "typescript-operations"
      - "typescript-vue-apollo-smart-ops"

这样codegen会直接从服务端获取包含分页类型的完整schema,与你的查询结构完全匹配。


方案二:手动补充分页类型到本地schema

如果不想依赖服务端,可手动在graphql/schema.graphql中添加Lighthouse分页相关的类型定义:

# 分页元数据类型
type PaginationMeta {
    currentPage: Int!
    lastPage: Int!
    perPage: Int!
    total: Int!
    from: Int!
    to: Int!
}

# 分页链接类型
type PaginationLinks {
    first: String!
    last: String!
    prev: String
    next: String
}

# 针对Post的分页结果类型
type PaginatedPostResult {
    data: [Post!]!
    meta: PaginationMeta!
    links: PaginationLinks!
}

type Query {
    posts: PaginatedPostResult! @paginate(defaultCount: 10)
}

# 确保已定义Post和User类型
type Post {
    uuid: ID!
    body: String!
    user: User!
}

type User {
    name: String!
}

修改后本地schema与查询结构一致,codegen即可正确生成类型定义。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 20:18:20