Like what we’re doing? Star us on GitHub!

Two-way relationship between fields

Daniq
4 weeks ago
2

I have a 2 collections:


const Users: CollectionConfig = {
fields:[
   {//working in companies
      name: "companies",
      type: "relationship",
      relationTo: "companies",
      hasMany: true,
  },
]}


const Companies: CollectionConfig = {
fields:[
   {//employees
      name: "workers",
      type: "relationship",
      relationTo: "users",
      hasMany: true,
  },
]}


Is there a way to

manage two-way relationship

?


When i'm adding a company in users

companies

then it will update this exact company and add this user to

workers

field, and vice versa for deleting?



I guess it should work similarly like relationships in keystonejs, where you can enter a field in a collection like "Companies.workers" and it will manage it by itself.



Maybe i've missed something in docs, but i didnt found a better solution than to add a lot of hooks for both fields and use

payload.update({})

to update another entity.

  • denolfe
    Payload Team
    4 weeks ago

    Payload does not have an official way to manage 2-way relationships. The hook method that you describe is used in this community plugin which may be what you need.

    https://github.com/TimHal/pcms-backpop
  • Daniq
    4 weeks ago

    Thanks, i've tried to use this one and i realized that for it breaks more than fixes, so i guess i will reformat my collections in some way to reduce relationships.

Open the post
Continue the discussion in Discord
Can't find what you're looking for?
Get help straight from the Payload team with an Enterprise License.Learn More