在 GraphQL 中对结果进行排序 (
排序定义返回的记录序列,并支撑稳定的分页。 在 GraphQL 中,数据 API 生成器 (DAB) 在应用或应用firstafter之前使用orderBy参数对结果进行排序。 如果省略 orderBy,DAB 默认按主键排序(升序)。
注释
复合主键按其数据库列序列进行排序。
转到 本文档的 REST 版本。
概述
| 概念 | Description |
|---|---|
| 论点 | orderBy |
| 方向值 |
ASC、DESC |
| 默认顺序 | 主键升序 |
| 多字段顺序 | 按声明的对象属性顺序排序 |
| 平局 | 自动追加的剩余主键字段 |
使用模式
query {
books(orderBy: { year: DESC, title: ASC }, first: 5) {
items {
id
title
year
}
}
}
概念 SQL
SELECT TOP (5)
id,
sku_title AS title,
year
FROM dbo.books
ORDER BY year DESC, sku_title ASC, id ASC;
示例响应
{
"data": {
"books": {
"items": [
{ "id": 7, "title": "Dune Messiah", "year": 1969 },
{ "id": 6, "title": "Dune", "year": 1965 },
{ "id": 3, "title": "Foundation", "year": 1951 },
{ "id": 1, "title": "I, Robot", "year": 1950 },
{ "id": 8, "title": "The Martian Chronicles", "year": 1950 }
]
}
}
}
字段行为
| 方面 | 行为 |
|---|---|
| 输入类型 | 生成的 *OrderByInput 枚举标量字段 |
| 方向枚举 |
ASC、DESC |
| 复合顺序 | 优先级遵循声明顺序 |
| Null 方向 | 从排序中排除字段 (title: null) |
| 未知字段 | 生成 GraphQL 验证错误 |
忽略字段的示例
query {
books(orderBy: { title: null, id: DESC }) {
items { id title }
}
}
无效结构
GraphQL 禁止在内部orderBy使用逻辑运算符 (and, or) 。 例如,以下代码生成验证错误:
books(orderBy: { or: { id: ASC } })
使用变量的示例
query ($dir: OrderBy) {
books(orderBy: { id: $dir }, first: 4) {
items { id title }
}
}
Variables
{ "dir": "DESC" }
相关配置
{
"entities": {
"Book": {
"source": {
"object": "dbo.books",
"type": "table"
},
"mappings": {
"sku_title": "title"
}
}
}
}
示例配置
{
"runtime": {
"pagination": {
"default-page-size": 100,
"max-page-size": 100000
}
},
"entities": {
"Book": {
"source": {
"type": "table",
"object": "dbo.books"
},
"mappings": {
"sku_title": "title",
"sku_price": "price"
},
"relationships": {
"book_category": {
"cardinality": "one",
"target.entity": "Category",
"source.fields": [ "category_id" ],
"target.fields": [ "id" ]
}
}
},
"Category": {
"source": {
"type": "table",
"object": "dbo.categories"
},
"relationships": {
"category_books": {
"cardinality": "many",
"target.entity": "Book",
"source.fields": [ "id" ],
"target.fields": [ "category_id" ]
}
}
}
}
}
另请参阅
| 概念 | REST | GraphQL | 目的 |
|---|---|---|---|
| 投影 | $select | 物品 | 选择要返回的字段 |
| Filtering | $filter | 滤波器 | 按条件限制行 |
| 排序 | $orderby | orderBy | 定义排序顺序 |
| 页面大小 | $first | first | 限制每页的项数 |
| 延续 | $after | 后 | 使用光标从最后一页继续 |
注释
REST 关键字以 $遵循 OData 约定开头。