Hi! I’m having trouble getting this relation working:
I have an IndexPage that will consume blog posts. When I’m editing IndexPage I have a list of blog posts so I can define the showing order.
I’m using this example: Stack overflow
config.yml
collections:
- name: "pages"
label: "Pages"
files:
- file: "src/pages/index.md"
name: "index"
label: "Landing Page"
fields:
- {
name: "templateKey",
label: "Template Key",
widget: "hidden",
default: "IndexPage",
}
- {
name: blogPosts,
label: Blog posts,
widget: list,
fields:
[
{
name: post,
label: Blog post,
widget: relation,
collection: blog,
value_field: title,
display_fields: [title],
search_fields: [title],
},
],
}
- name: "blog"
label: "Blog"
folder: "src/pages/blog"
preview_path: blog/{{slug}}
create: true
slug: "{{slug}}-{{year}}-{{month}}-{{day}}"
fields:
- {
label: "Template Key",
name: "templateKey",
widget: "hidden",
default: "blogPage",
}
- { label: Title, name: title, widget: string }
- { label: Date, name: date, widget: date }
node-config
exports.sourceNodes = ({ actions, getNode, getNodes }) => {
const { createNodeField } = actions;
const blogPosts = {};
const markdownNodes = getNodes()
.filter(node => node.internal.type === "MarkdownRemark")
.forEach(node => {
if (node.frontmatter.blogPosts) {
getNodes()
.forEach(node2 => {
if (node2.internal.type === "MarkdownRemark" && node2.frontmatter.templateKey === 'blogPage') {
let blogPostNode;
node.frontmatter.blogPosts.forEach(
post => {
if (post.post === node2.frontmatter.title) {
blogPostNode = node2;
}
}
);
if (blogPostNode) {
if (!(blogPostNode.id in blogPosts)) {
blogPosts[blogPostNode.id] = []
}
blogPosts[blogPostNode.id].push(node.id);
}
}
});
}
});
Object.entries(blogPosts).forEach(([pageNodeId, postIds]) => {
console.log(pageNodeId, postIds);
createNodeField({
node: getNode(pageNodeId),
name: "blogPosts",
value: postIds,
});
});
}
gatsby-config
mapping: {
"MarkdownRemark.fields.blogPosts": "MarkdownRemark"
}
query
query MyQuery {
markdownRemark(frontmatter: {templateKey: {eq: "IndexPage"}}) {
fields {
blogPosts {
id
}
}
frontmatter {
title
banner {
paragraph
}
hero {
subHeading
}
}
}
}
query result
{
"data": {
"markdownRemark": {
"fields": {
"blogPosts": null
},
"frontmatter": {
"title": "",
"banner": {
"paragraph": "Founded in 2009, we are a technical company at heart: Software Engineers, Designers and Architects with a passion for helping our clients navigate change and better integrate technology into their processes."
},
"hero": {
"subHeading": "We help SMBs and Fortune 500 companies leverage technology to enhance processes, improve efficiency and connect better."
}
}
}
},
"extensions": {}
}