在AWS AppSync中,您可以使用@connection
指令来过滤列表。@connection
指令允许您在GraphQL模型中定义关联关系,并支持过滤和排序。以下是一个包含代码示例的解决方法:
首先,假设您有两个GraphQL模型:User
和Post
。User
拥有多个Post
,每个Post
有一个userId
字段来标识所属的User
。
type User {
id: ID!
name: String!
posts: [Post] @connection(keyName: "byUser", fields: ["id"])
}
type Post {
id: ID!
title: String!
content: String!
userId: ID!
user: User @connection(fields: ["userId"])
}
在上面的代码中,User
模型通过@connection
指令定义了与Post
模型的关联关系,并指定了keyName
为"byUser",fields
为["id"]。这意味着我们可以在User
模型上使用过滤器来过滤Post
列表。
接下来,您可以在AWS AppSync的数据源中使用以下代码示例来过滤Post
列表:
query listPostsByUser($userId: ID!) {
listPosts(filter: { user: { id: { eq: $userId } } }) {
items {
id
title
content
user {
id
name
}
}
}
}
在上面的代码中,我们使用filter
参数来过滤listPosts
查询的结果。通过指定user.id
的值等于给定的userId
,我们可以过滤只返回属于该用户的Post
。
您可以将上述查询与AWS AppSync的客户端SDK(如AWS Amplify)一起使用,以便在您的应用程序中执行该查询。