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

AWS Amplify:@belongsTo结合@auth多排序键时推送失败求助

解决AWS Amplify中@belongsTo与多索引父元素结合的报错问题

问题描述

执行amplify push推送Schema时触发以下错误:

🛑 Invalid @belongsTo on Comments:todo. Provided fields do not match the size of primary key(s) for Todos

核心原因是父模型Todos定义了多个带排序键的全局二级索引,Amplify解析@belongsTo关联时混淆了主键结构;同时Comments中message字段的@belongsTo存在语法错误,且Messages的@hasMany索引名与Comments的索引不匹配。

修正后的Schema

type Todos @model @auth(rules: [{ allow: public }]) {
  id: ID!
  createdAt: String
  number: Int
  title: String
  description: String
  comments: [Comments] @hasMany(indexName: "byComments", fields: ["id"])
  baseType: String
    @index(
      name: "byNumber"
      queryField: "todosByNumber"
      sortKeyFields: ["number"]
    )
    @index(
      name: "byTitle"
      queryField: "todosByTitle"
      sortKeyFields: ["title"]
    )
    @index(
      name: "byDescription"
      queryField: "todosByDescription"
      sortKeyFields: ["description"]
    )
}

type Comments @model @auth(rules: [{ allow: public }]) {
  id: ID!
  todosID: ID! @index(name: "byComments")
  # 明确指定关联Todos的主主键id
  todo: Todos @belongsTo(fields: ["todosID"], targetName: "id")
  createdAt: String
  firstName: String
  lastName: String
  messageID: ID @index(name: "commentsByMessages")
  # 修正fields为数组格式,符合语法规范
  message: Messages @belongsTo(fields: ["messageID"])
}

type Messages @model @auth(rules: [{ allow: public }]) {
  id: ID!
  title: String
  content: String
  # 匹配Comments中messageID的索引名,保证关联生效
  comments: [Comments] @hasMany(indexName: "commentsByMessages", fields: ["id"])
}

关键修正说明

  1. 明确@belongsTo关联目标:给Comments.todo的@belongsTo添加targetName: "id"参数,强制指定关联Todos的主主键字段,避免Amplify因多索引混淆主键结构。
  2. 修正语法错误:将Comments.message的@belongsTo中fields: "messageID"改为数组格式fields: ["messageID"],符合Amplify Schema的语法要求。
  3. 对齐索引名:调整Messages.comments的@hasMany索引名为commentsByMessages,与Comments.messageID的索引名保持一致,确保关联关系正常生效。

完成以上修改后,重新执行amplify push即可成功部署Schema。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 12:01:00