首页 > 解决方案 > 如何正确处理同名反向关系

问题描述

我有一种情况,有多个具有相同字段的部分。但是,当使用反向关系时,就会出现问题,因为它们似乎无法共存:

{
  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
    }
  },
},

事件类型覆盖组织类型。这是这两种类型都具有的字段(对于 DRY):

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

我尝试使用idsFieldand reverseOf,但都失败了。人类型能够获得其他两种类型的反向关系的适当策略是什么?

标签: apostrophe-cms

解决方案


在筛选 ApostropheCMS 文档时,我通过反复试验找到了答案。我想我会在这里分享我的解决方案,以防其他人偶然发现相同类型的问题:

{
  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
    }
  },
},

请注意namereverseOfwithType属性,这是确保避免覆盖结果的方法。

然后可以使用data.piece._organizationsanddata.piece._events并获取_relatedPeoplefor each。


推荐阅读