简体   繁体   中英

Sorting GraphQL query on multiple queries in Gatsby

I'm using Gatsby as my static generator and Contentful as my datasource.

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. So far I have the following which returns each contentType in order of each contentType but not in order of date overall.

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

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")
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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