首页 > 解决方案 > 使用 Amplify GraphQL Data 对查询列表进行排序,无需任何其他字段匹配

问题描述

我正在一起研究 Next.js 和 Amplify,试图让排序与数据库一起工作。

为什么我们不能只按 DESC 或 ASC 对查询列表进行排序?为什么我们必须创建一个新键并为其添加额外的字段?

例如:

type Order @model @key(fields: ["customerEmail", "createdAt"]) {
  id: ID!  
  customerEmail: String!
  createdAt: String!
  orderId: ID!
}

将允许您使用 customerEmail 获取所有订单,然后您可以执行sortDirection此操作,并且仅当您有另一个customerEmail要填充的字段时才有效:

await API.graphql(listOrders, {
  customerEmail: "some@email.com",
  sortDirection: "DESC", // or ASC
})

这将为您提供订单列表,some@email.com并允许您进行排序。

为什么我们不能只拥有该id字段并排序:

type Order @model @key(name: "orderSort", fields: ["id", "createdAt"], queryField: "orderSort") {
  id: ID!  
  customerEmail: String!
  createdAt: String!
  orderId: ID!
}

并对列表进行排序:

await API.graphql(orderSort, {
  sortDirection: "DESC", // or ASC
})

我尝试了类似的方法,但出现错误:Expression block '$[query]' requires an expression.


或者为什么即使没有@key指令我们也不能只进行排序,只需使用带有 sortDirection 的 listOrders:

type Order @model {
  id: ID!  
  customerEmail: String!
  createdAt: String!
  orderId: ID!
}

await API.graphql(listOrders, {
  sortDirection: "DESC", // or ASC
})

标签: graphqlnext.jsamazon-dynamodbaws-amplifydynamodb-queries

解决方案


DynamodbSCAN运营商不保证订单。

目前,Amplify 默认也不支持排序。

然而,显然,大多数人所做的就是在模型中添加一个常量字段。

type Order @model @key(name: "orderSort", fields: ["typename", "createdAt"], queryField: "orderSort") {
  id: ID! 
  customerEmail: String!
  typename: String! # for example, Order in this case 
  createdAt: AWSDateTime!
}
await API.graphql(orderSort, {
  typename: "Order",
  sortDirection: "DESC", // or ASC
})

推荐阅读