我有一个student
模型,一个favorite
模型和媒体模型,例如music
,video
等。我想实现hasManyThrough
多态关系,其中直通模型为favorite
,然后在我的案例mongoDB中将这些收藏夹存储在favorite
表中。是否正在使用loopback3,有关此主题的文档尚不清楚。有线索吗?
答案 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": {}
}
然后,您只需要发布具有属性Favorite
和studentId
的新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": {}
}