简体   繁体   English

在 Gatsby 中对多个查询排序 GraphQL 查询

[英]Sorting GraphQL query on multiple queries in Gatsby

I'm using Gatsby as my static generator and Contentful as my datasource.我使用 Gatsby 作为我的静态生成器,使用 Contentful 作为我的数据源。

We've got multiple contentTypes in Contentful (blog, event, whitepaper) and I want to return these in within one query and sorted by createdAt date.我们在 Contentful(博客、事件、白皮书)中有多个 contentType,我想在一个查询中返回这些内容并按 createdAt 日期排序。 So far I have the following which returns each contentType in order of each contentType but not in order of date overall.到目前为止,我有以下内容,它按每个 contentType 的顺序返回每个 contentType,但不按整个日期的顺序返回。

Is there a way I can do a sort across the entire query?有没有办法可以对整个查询进行排序?

{
    whitepapers: allContentfulWhitepaper(sort: { order: DESC, fields: createdAt }) {
      edges {
        node {
          id
          slug
          title
        }
      }
    }
    blogs: allContentfulBlogPost(sort: { order: DESC, fields: createdAt }) {
      edges {
        node {
          id
          slug
          title
        }
      }
    }
    events: allContentfulEventPage(sort: { order: DESC, fields: createdAt }) {
      edges {
        node {
          id
          slug
          title
        }
      }
    }
  }

I don't think GraphQL query is able to do the sorting across multiple fields, but you can sort in component我不认为 GraphQL 查询能够跨多个字段进行排序,但您可以在组件中进行排序

import React from 'react';
import { graphql } from 'gatsby';

const IndexPage = ({ data }) => {
  const { whitepapers, blogs, events } = data;
  const allDataInDesc = [
    ...whitepagers.edges.map(e => e.node),
    ...blogs.edges.map(e => e.node),
    ...events.edges.map(e => e.node),
  ].sort((a, b) => { return new Date(a.createdAt) > new Date(b.createdAt) ? -1 : 1; });

  return <>...</>
}

export const query = graphql`
  {
    whitepapers: allContentfulWhitepaper(sort: { order: DESC, fields: createdAt }) {
      edges {
        node {
          id
          slug
          title
          createdAt
        }
      }
    }
    blogs: allContentfulBlogPost(sort: { order: DESC, fields: createdAt }) {
      edges {
        node {
          id
          slug
          title
          createdAt
        }
      }
    }
    events: allContentfulEventPage(sort: { order: DESC, fields: createdAt }) {
      edges {
        node {
          id
          slug
          title
          createdAt
        }
      }
    }
  }
`;

export default IndexPage;

Sure you can sort by multiple fields.当然,您可以按多个字段排序。 Just pass fields and sort order as an array to your query:只需将字段和排序顺序作为数组传递给您的查询:

query MyQuery {
    allContentfulPost(
        sort: { fields: [featured, updatedAt], order: [ASC, DESC] }) {
        edges {
            node {
               featured
               updatedAt(formatString: "d MM yyyy")
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM