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

求助:无法编辑AWS AppSync中@manyToMany生成的OrderUsers实体

解决Amplify @manyToMany生成中间表无法自定义修改的问题

问题根源

Amplify的@manyToMany注解是自动生成中间关联表,该表的结构由Amplify内部维护,不会写入schema.graphql文件。因此直接修改数据库中的中间表(如添加GSI、改分区键、加字段),在执行amplify push/pull时会被Amplify基于原schema重新生成的结构覆盖,所有自定义修改都会丢失。

解决方案:手动定义中间关联表

要实现自定义修改并保留变更,需要放弃自动生成的@manyToMany,手动创建中间表实体并通过@hasMany/@belongsTo建立关联。这样中间表的定义会写入schema,Amplify会基于该定义维护表结构,自定义配置不会被覆盖。

修改后的Schema示例

type User @model {
  id: ID! 
  fName: String!
  lName: String!
  phoneNumber: String!
  email: String!
  DOB: String!
  # 替换原@manyToMany,关联到手动定义的中间表
  orderUsers: [OrderUser] @hasMany(indexName: "byUser", fields: ["id"])
  ordersByDate: [Order] @hasMany(indexName: "byOrderByDate", fields: ["id"])
  ordersByStatusDate: [Order] @hasMany(indexName: "byOrderStatusByDate", fields: ["id"])
}

type Order @model {
  id: ID!
  userId: ID! @index(name: "byOrderStatusByDate", sortKeyFields: ["status", "date"]) @index(name: "byOrderByDate", sortKeyFields: ["date"])
  status: String!
  amount: Int
  date: String!
  # 替换原@manyToMany,关联到手动定义的中间表
  orderUsers: [OrderUser] @hasMany(indexName: "byOrder", fields: ["id"])
  productId: ID! @index(name: "byProductOrder", sortKeyFields: ["id"])
  clubId: ID! @index(name: "byClub", sortKeyFields: ["id"])
}

# 手动定义中间关联表,可自由添加字段、索引、复合键
type OrderUser @model {
  id: ID!
  userId: ID! @index(name: "byUser", sortKeyFields: ["orderId"])
  orderId: ID! @index(name: "byOrder", sortKeyFields: ["userId"])
  # 自定义字段示例:关联创建时间
  createdAt: String!
  # 自定义GSI示例
  @index(name: "byCreatedAt", sortKeyFields: ["createdAt"])
  # 复合分区键配置示例(如需)
  # @key(fields: ["userId", "orderId"])
}

操作步骤

  1. 删除原Schema中User和Order类型里的@manyToMany注解,替换为@hasMany关联到新的OrderUser类型
  2. 添加OrderUser实体,按需定义字段、索引、键结构
  3. 执行amplify push,确认变更后Amplify会生成对应的表、解析器,所有自定义配置会被永久保留
  4. 若之前已有自动生成的OrderUsers表数据,需手动迁移到新表,或在Amplify控制台删除旧表避免冲突

注意事项

  • 后续建立用户与订单的关联,需通过createOrderUser mutation操作中间表,而非原自动生成的关联方法
  • 查询关联数据时,需通过中间表跳转,例如从用户查订单:user.orderUsers.items[0].order

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 05:05:39