首次编写GraphQL Schema遇AWS Amplify旧指令报错求助
问题原因与修正方案
错误原因
你的GraphQL Schema使用了Amplify GraphQL Transformer v1的@connection和旧版@key语法,而当前Amplify默认启用的是v2版本Transformer,两者语法不兼容,导致部署报错。
核心修正要点
v2版本Transformer中,关联关系通过@hasMany(一对多)和@belongsTo(多对一)指令替代旧的@connection,全局二级索引(GSI)改用@index定义,而非旧版@key。
修正后的完整Schema代码
input AMPLIFY { globalAuthRule: AuthRule = { allow: public } } # FOR TESTING ONLY! type User @model { id: ID! username: String! # 一对多关联:一个用户对应多条帖子,关联索引为byUser posts: [Post] @hasMany(indexName: "byUser", fields: ["id"]) } type Post @model @index(name: "byUser", fields: ["userID"]) @index(name: "bySong", fields: ["songID"]) { id: ID! videoUri: String! description: String! userID: ID! # 多对一关联:多条帖子属于一个用户,关联字段为userID user: User @belongsTo(fields: ["userID"]) songID: ID! # 多对一关联:多条帖子关联一首歌曲,关联字段为songID song: Song @belongsTo(fields: ["songID"]) } type Song @model { id: ID! name: String! imageUri: String! # 可选:反向关联一首歌曲对应的所有帖子 posts: [Post] @hasMany(indexName: "bySong", fields: ["id"]) }
关键细节说明
关联关系调整
@hasMany用于父类型(如User、Song)定义到子类型(Post)的一对多关联,需指定索引名和关联字段@belongsTo用于子类型(Post)定义到父类型(User、Song)的多对一关联,需指定关联字段
索引定义调整
- 用
@index替代旧版@key来定义全局二级索引,确保关联查询可以高效执行
- 用
可选反向关联
- Song类型中的
posts字段为可选,若不需要从歌曲维度查询关联帖子,可直接删除该字段及对应的@index(name: "bySong", fields: ["songID"])
- Song类型中的
修改完成后,重新执行amplify push即可完成API部署。
内容的提问来源于stack exchange,提问作者Ashray Jha
相关产品推荐
相关产品推荐

