Relations Best Practive?

default discord avatar
alphamoonbase.berlin
last month
5

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:


https://github.com/payloadcms/payload/issues/72

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.

  • discord user avatar
    jarrod_not_jared
    Payload Team
    last month

    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

  • default discord avatar
    alphamoonbase.berlin
    last month

    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.)?

  • discord user avatar
    jarrod_not_jared
    Payload Team
    last month

    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

  • default discord avatar
    alphamoonbase.berlin
    last month

    It would need to be update via a hook, for sure!



    I think I will try both. 🙂

  • discord user avatar
    jarrod_not_jared
    Payload Team
    last month

    sweet, have fun! 🙂

Open the post
Continue the discussion in Discord
Like what we're doing?
Star us on GitHub!

Star

Connect with the Payload Community on Discord

Discord

online

Can't find what you're looking for?

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