Let's say I have classic articles - tags relationships.
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?
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.
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
Discord
online
Get dedicated engineering support directly from the Payload team.