Search code examples
apostrophe-cms

How to properly handle a reverse relationship with the same name


I have a situation where there are multiple pieces with the same field. However, when going with the reverse relationship, it becomes a problem because they cannot seem to coexist:

{
  name: '_relatedPeople',
  type: 'joinByArrayReverse',
  withType: 'organization',
  filters: {
    projection: {
      _url: 1,
      title: 1,
      tags: 1
    }
  },
},
{
  name: '_relatedPeople',
  type: 'joinByArrayReverse',
  withType: 'event',
  filters: {
    projection: {
      _url: 1,
      title: 1,
      tags: 1
    }
  },
},

The event type overwrites the organization type. Here is the field that both those types have (for DRY):

{
  "label": "Related People",
  "help": "",
  "name": "_relatedPeople",
  "type": "joinByArray",
  "withType": ["person"],
  "filters": {
    "projection": {
      "_url": 1,
      "title": 1
    }
  }
}

I tried using idsField and reverseOf, and both failed miserably. What is the appropriate strategy for the person type to be able to get the reverse relationship of the other two types?


Solution

  • I found an answer by trial and error while sifting through the ApostropheCMS doc. I thought I'd share my solution here, in case others stumble on the same type of issue:

    {
      name: '_organizations', // type from which to get the pieces, prefixed with "_" and suffixed with "s"
      reverseOf: '_relatedPeople', // field name from which to get the pieces
      type: 'joinByArrayReverse',
      withType: 'organization', // type which holds the pieces
      filters: {
        projection: {
          _url: 1,
          title: 1
        }
      },
    },
    {
      name: '_events', // type from which to get the pieces, prefixed with "_" and suffixed with "s"
      reverseOf: '_relatedPeople', // field name from which to get the pieces
      type: 'joinByArrayReverse',
      withType: 'event', // type which holds the pieces
      filters: {
        projection: {
          _url: 1,
          title: 1
        }
      },
    },
    

    Note the name, reverseOf, and withType properties, which is how you can ensure to avoid overwriting the results.

    It is then possible to use data.piece._organizations and data.piece._events and get the _relatedPeople for each.