双重多对多关系

时间:2016-05-12 06:32:25

标签: javascript loopbackjs strongloop

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

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"
      }]
    }

显然,行动现在通过基准作为主要关系附加。这怎么发生的?我的模型设置错了吗?

1 个答案:

答案 0 :(得分:1)

根据我的理解,当你使用hasAndBelongsToMany relashionship时,loopback会使用一个自动为你管理的直通表。

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

尝试通过选项,例如

动作

"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