在数据模型中使用Amplify时,@hasMany关系有可能返回null。这通常是因为关联对象没有正确地加载。为了解决这个问题,可以尝试以下方法:
例如,考虑一个数据模型,子对象通过“parentId”字段与父对象相连。要正确地使用@hasMany关系,必须定义关联如下:
type Parent @model {
id: ID!
name: String!
children: [Child] @hasMany(indexName: "byParent", fields: ["id"])
}
type Child @model {
id: ID!
name: String!
parentId: ID!
parent: Parent @belongsTo(indexName: "byParent", fields: ["parentId"])
}
例如,要查询所有父对象及其子对象,可以通过以下方式执行查询:
Amplify.API.query(Parent, "byId", { id: 1 }, { limit: 10, children: { limit: 20 }})
.then(data => console.log(data))
.catch(error => console.log(error))
在这个例子中,我们指定了“children”参数来表示要查询的所有子对象,并且指定了查询限制。
通过这些步骤,可以解决Amplify @hasMany关系返回null的问题并正确加载关联对象。