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

default discord avatar
hunghvu2 years ago
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,
        }
...

image

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
    DanRibbens
    2 years ago

    There are several lengthy discussions on this already:
    #204
    #357

    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: https://github.com/payloadcms/public-demo/blob/master/src/components/CategorySummary/index.tsx

    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
    Snailedlt12 months ago

    The link no longer works since the codebase changed... Here's a permalink to the commit: https://github.com/payloadcms/public-demo/blob/501e2e1bf73501fbfd9e140f81b28601ab9ff01e/src/components/CategorySummary/index.tsx

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

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