排序

Payload 中的文档可以轻松通过特定字段进行排序。查询文档时,你可以传递任何顶级字段的名称,响应结果将按该字段以_升序_排列文档。如果字段名前加上减号("-"),则会以_降序_排序。在 Local API 中,可以通过字符串数组指定多个排序字段。在 REST API 中,可以通过逗号分隔多个字段。减号可以单独应用于各个字段前。

由于排序由数据库处理,该字段不能是虚拟字段,除非它与关系字段关联。字段必须存储在数据库中才能被搜索。

提示: 出于性能考虑,建议对需要排序的字段启用 index: true更多详情

Local API

要在Local API中对文档进行排序,可以在查询中使用sort选项:

import type { Payload } from 'payload'

const getPosts = async (payload: Payload) => {
  const posts = await payload.find({
    collection: 'posts',
    sort: '-createdAt', // highlight-line
  })

  return posts
}

要通过多个字段排序,可以使用包含字段的数组作为sort选项:

import type { Payload } from 'payload'

const getPosts = async (payload: Payload) => {
  const posts = await payload.find({
    collection: 'posts',
    sort: ['priority', '-createdAt'], // highlight-line
  })

  return posts
}

REST API

REST API 中进行排序时,可以在查询中使用 sort 参数:

fetch('https://localhost:3000/api/posts?sort=-createdAt') // highlight-line
  .then((response) => response.json())
  .then((data) => console.log(data))

如需按多个字段排序,可以使用 sort 参数并用逗号分隔字段:

fetch('https://localhost:3000/api/posts?sort=priority,-createdAt') // highlight-line
  .then((response) => response.json())
  .then((data) => console.log(data))

GraphQL API

GraphQL API 中进行排序时,可以在查询中使用 sort 参数:

query {
  Posts(sort: "-createdAt") {
    docs {
      color
    }
  }
}