Contentful logo

Contentful Community

Best way to model a two-way relationship for "related articles"

I am new to Contentful and so far I love using the service.

I’m not sure how to structure my content models to implement a two-way relationships between models. Say I have Article A and Article B and I want to express the notion that “Article A is related to Article B” (consequently implying that Article B is also related to Article A).

I could add a “Related Articles” field of type “Link” on my “Article” model. But it doesn’t feel very robust.

Let’s go through a simple scenario:

  • In the web editor, when editing Article A, I link to Article B from the “Related Articles” field.
  • Then on my website, on the page displaying Article A, “Article B” will naturally show up in the “Related Articles” field. So far, so good.
  • But what about the web page displaying Article B? I’d like “Article A” to show up in its “Related Articles” section but how does that work? I can certainly query for all articles linking to “the current article”, and “Article A” will be retrieved. But Article B could also have its own links in its “Related Articles” field. So now I have to merge the articles from the “Related Articles” field + the articles returned by the query. And what if I inadvertently also link from Article B to Article A, creating a double?

In traditional SQL, I would create a cross-reference table with the sole purpose of storing the relationship (see https://en.wikipedia.org/wiki/Many-to-many_(data_model)) but I’m not sure it’s the right thing to do with Contentful. Also, that would impose a burden on content creators who would have to edit two pieces of content instead of one (the article AND the relationship).

Any suggestion would be appreciated.

1 Like

Hi @vincedo :wink:

Thank you very much for your feedback and I’m incredibly happy you like it so far!
What you’re talking about is a well known case. Right now, in Contentful you can create parent-child relation, meaning: parent entry would have a link to child, but not vice versa. When you would call parent entry, you’ll see the child entry, but if you would call child entry, parent entry won’t be shown in the response.
The workaround for two-way links is- create reference fields in both entries. So both entries will become parent and child for each other.
That’s sort of many-to-many as mentioned.

That is true, unfortunately… :cry:

Alright. Thanks for the prompt reply, @andrey.

1 Like

@vincedo Sure thing!

Let me know if you need any further assistance.

Looking into doing something similar, but can’t expect external content editors to update all related items in multiple places, that will definitely create a mess.

Since this item is over 2 years old: is there currently a better way of handling this? Or maybe a workaround via a tool like Zapier that updates related items?