What would be the best practive to handle Relationships between collections?
i.E. I have a page and Several Posts. On page can have any page but a post can only have on page.
In this case I would create a relationShip entry at my posts pointing at my page.
Pretty streight forward. But when I now query the Page via my API, I would not get the posts per default, as the relation is onsided atm.
Is there a way to tell the Page-Collection to query for Posts with itself as owner?
I suppose my queston is if there is a nice way of creating a two way relation between collections.
Came accros this issue on github:
It pretty much describes what I am after.
Hmmm. Ok. Seems like I need to use a hook to populate the content dynamicly. Can do!
https://payloadcms.com/blog/learn-how-virtual-fields-can-help-solve-common-cms-challenges
Idea is to create a hook the fires after update on the single entity, forcing an update of the data of the parent.
I would probably create a relationship field on your pages, with relationTo set to
posts
, but make the field
admin.hidden
, then populate that fields data with an afterRead hook (at the collection level). This way your TS types / GraphQL schema will still be correct
Ok. Got it setup in this way and seems to work. Only downside is that the subQuerry is run every time we access that field in the api.
What would be the downside of writing the values directly in (except of course for having more then one source.)?
It becoming out of date, that is the only downside
but a totally valid option
and you could keep it up to date with hooks on your posts collection
It would need to be update via a hook, for sure!
I think I will try both. 🙂
sweet, have fun! 🙂
Star
Discord
online
Get help straight from the Payload team with an Enterprise License.