hasManyThrough多态关系

问题描述 投票:0回答:1

我有一个student模型,一个favorite模型和媒体模型,例如musicvideo等。我想实现hasManyThrough ploymorphic关系,其中直通模型是favorite然后将这些收藏夹存储在我的案例mongoDB中的favorite表中。我使用loopback3及其文档并不清楚这个主题。任何领导?

node.js loopbackjs
1个回答
0
投票

你的模型看起来像这样:

通用/模型/ 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": {}
}

通用/模型/ 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": {}
}

通用/模型/ 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

通用/模型/ 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": {}
}
© www.soinside.com 2019 - 2024. All rights reserved.