How to concurrently update items in 2 collections with many-to-many relationship?

default discord avatar
hunghvulast year
2 1

Let's say I have classic articles - tags relationships.

  1. One article has many tags.
  2. One tag has many articles.
  3. When the user clicks on a tag, it leads to a respective tag page with a list of articles.

I believe it is possible to add tags (not a collection) to articles (is a collection) and use a query to filter out accordingly, however, I would like to separate tags and articles into 2 separate collections instead. For example:

// Tags.ts
          name: 'usedByArticles',
          type: 'relationship',
          relationTo: 'articles',
          hasMany: true,


This portion of code allows me to add articles to a tag. However, the reversed direction is not updated accordingly (the article does not know it has a tag). With that said, how to make the update bi-directional?

  • Selected Answer
    discord user avatar
    last year

    There are several lengthy discussions on this already:

    You should only do hooks to update other documents like this if you absolutely have to. Maintaining the same data in two places usually isn't the best solution.
    If you wanted to have a list of articles for a tag, it is easy to query that info if you just have a tags relationship in the articles collection. The way we handled this in the public-demo was a category summary UI field:

    Another option to make a 3rd collection that acts like a join table. The collection would have 2 relationship fields, one for article and one for tag. Each document in this collection represents one tag for one article. It might not make things easier for data entry and you might still need hooks, but it would be a clean solution on the data and could be good for querying also.

    1 reply
  • default discord avatar
    Snailedlt9 months ago

    The link no longer works since the codebase changed... Here's a permalink to the commit:

Star on GitHub


Chat on Discord



Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.