hasManyThrough多态关系

时间:2019-03-25 13:35:27

标签: node.js loopbackjs

我有一个student模型,一个favorite模型和媒体模型,例如musicvideo等。我想实现hasManyThrough多态关系,其中直通模型为favorite,然后在我的案例mongoDB中将这些收藏夹存储在favorite表中。是否正在使用loopback3,有关此主题的文档尚不清楚。有线索吗?

1 个答案:

答案 0 :(得分:0)

您的模型如下所示:

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": {}
}

然后,您只需要发布具有属性FavoritestudentId的新videoId项即可添加新关系。

编辑:添加了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": {}
}