双重多对多关系

Double many-to-many relationship

在环回中我定义了两个具有双重多对多关系的模型如下:

action.json:

    {
      "name": "Action",
      "base": "PersistedModel",
      "idInjection": true,
      "options": {
        "validateUpsert": true
      },
      "properties": {
        "text": {
          "type": "string",
          "required": true
        }
      },
      "validations": [],
      "relations": {
        "benchmark": {
          "type": "hasAndBelongsToMany",
          "model": "Course",
          "foreignKey": "benchmark"
        },
        "main": {
          "type": "hasAndBelongsToMany",
          "model": "Course",
          "foreignKey": "main"
        }
      },
      "acls": [],
      "methods": {}
    }

course.json:

    {
      "name": "Course",
      "base": "TrashModel",
      "idInjection": true,
      "options": {
        "validateUpsert": true
      },
      "properties": {
        "name": {
          "type": "string",
          "required": true
        }
      },
      "validations": [],
      "relations": {
        "benchmark": {
          "type": "hasAndBelongsToMany",
          "model": "Action",
          "foreignKey": "benchmark"
        },
        "main": {
          "type": "hasAndBelongsToMany",
          "model": "Action",
          "foreignKey": "main"
        }
      },
      "acls": [],
      "methods": {}
    }

现在,当我尝试使用以下 PUT 请求在操作模型和课程模型之间创建关系时:

http://localhost:3000/api/courses/57331a4eeff440cb02c886ae/benchmark/rel/5731d60da2c6d238e3c3d9b3

然后,当我使用以下 GET 请求中包含的相关操作模型请求课程模型时:

http://localhost:3000/api/courses/57331a4eeff440cb02c886ae?filter=%7B%22include%22%3A%5B%22benchmark%22%2C%22main%22%5D%7D

我得到:

    {
      "name": "Introduction Lessons",
      "id": "57331a4eeff440cb02c886ae",
      "benchmark": [{
        "text": "text here",
        "id": "5731d60da2c6d238e3c3d9b3"
      }],
      "main": [{
        "text": "text here",
        "id": "5731d60da2c6d238e3c3d9b3"
      }]
    }

很明显,动作现在是通过基准作为主要关系附加的。这怎么发生的?我的模型设置有误吗?

据我了解,当您使用 hasAndBelongsToMany 关系时,loopback 使用它自动为您管理的直通 table。

我相信默认情况下它会调用自己 From_modelTo_model。为了有两个这样的关系,你需要告诉环回以不同的方式管理它,否则他们通过 table.

使用相同的

尝试使用 through 选项,例如

动作

"benchmark": {
  "type": "hasAndBelongsToMany",
  "model": "Course",
  "foreignKey": "benchmark",
  "through":"ActionCourseBenchmark"
},
"main": {
  "type": "hasAndBelongsToMany",
  "model": "Course",
  "foreignKey": "main",
  "through":"ActionCourseMain"
}

课程

"benchmark": {
  "type": "hasAndBelongsToMany",
  "model": "Action",
  "foreignKey": "benchmark",
  "through":"ActionCourseBenchmark"
},
"main": {
  "type": "hasAndBelongsToMany",
  "model": "Action",
  "foreignKey": "main",
  "through":"ActionCourseMain"
}

有关详细信息,请参阅 this github issue