hasManyThrough 多态关系

hasManyThrough polymorphic relation

我有一个 student 模型、一个 favorite 模型和媒体模型,例如 musicvideo 等。我想实现 hasManyThrough 多态关系其中直通模型是 favorite,然后将这些收藏夹存储在 favorite table 中,在我的例子中是 mongoDB。我正在使用 loopback3,它的文档对此 topic.Any 线索不清楚?

您的模型将如下所示:

common/models/student.json

{
  "name": "Student",
  "base": "User",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {

  },
  "validations": [],
  "relations": {
    "favorites": {
      "type": "hasMany",
      "model": "Favorite",
      "foreignKey": "studentId"
    },
    "videos": {
      "type": "hasMany",
      "model": "Video",
      "foreignKey": "studentId",
      "through": "Favorite",
      "keyThrough": "favoriteId"
    },
    "musics": {
      "type": "hasMany",
      "model": "Music",
      "foreignKey": "studentId",
      "through": "Favorite",
      "keyThrough": "favoriteId"
    }
  },
  "acls": [],
  "methods": {}
}

common/models/video.json

{
  "name": "Video",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {

  },
  "validations": [],
  "relations": {
    "favorites": {
      "type": "hasMany",
      "model": "Favorite",
      "foreignKey": "videoId"
    },
    "students": {
      "type": "hasMany",
      "model": "Student",
      "foreignKey": "videoId",
      "through": "Favorite",
      "keyThrough": "studentId"
    }
  },
  "acls": [
  ],
  "methods": {}
}

common/models/favorite.json

{
  "name": "Favorite",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {

  },
  "validations": [],
  "relations": {
    "student": {
      "type": "belongsTo",
      "model": "Student",
      "foreignKey": "studentId"
    },
    "video": {
      "type": "belongsTo",
      "model": "Video",
      "foreignKey": "videoId"
    },
    "music": {
      "type": "belongsTo",
      "model": "Music",
      "foreignKey": "musicId"
    }
  },
  "acls": [],
  "methods": {}
}

然后,您只需 POST 一个具有 studentIdvideoId 属性的新 Favorite 项来添加新关系。

编辑:添加了music.json

common/models/music.json

{
  "name": "Music",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {

  },
  "validations": [],
  "relations": {
    "favorites": {
      "type": "hasMany",
      "model": "Favorite",
      "foreignKey": "musicId"
    },
    "students": {
      "type": "hasMany",
      "model": "Student",
      "foreignKey": "musicId",
      "through": "Favorite",
      "keyThrough": "studentId"
    }
  },
  "acls": [
  ],
  "methods": {}
}