我试图理解Loopback中关系的工作原理。假设有一个游戏模型,对于一个游戏,有两个团队(主场和客场)。以下是我定义的方法:
{
"name": "Game",
"plural": "games",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"gameId": {
"type": "number",
"required": true,
"id": true
},
},
"validations": [],
"relations": {
"homeTeam": {
"type": "belongsTo",
"model": "Team",
"foreignKey": ""
},
"awayTeam": {
"type": "belongsTo",
"model": "Team",
"foreignKey": ""
},
},
"acls": [],
"methods": {}
}
所以主队和客队都属于一个团队对象。这是我的团队模型:
{
"name": "Team",
"plural": "teams",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"teamId": {
"type": "number",
"required": true,
"id": true
},
"validations": [],
"relations": {
"games": {
"type": "hasMany",
"model": "Game",
"foreignKey": "teamId"
}
},
"acls": [],
"methods": {}
}
所以一支球队可以有很多比赛。这对我来说听起来不错。当我去http://localhost:3000/api/games/1871811/homeTeam
时,它会正确显示该游戏中的主队。客队也是如此。但是当我转到http://localhost:3000/api/teams/53/games
时,它只会以[]
回复。我很确定这些ID是正确的。
我在这里做错了什么?
答案 0 :(得分:0)
在游戏中,您不需要为其ID设置属性。 loopback将自动创建自动增量ID。游戏桌应该保留TeamId和homeTeamId,以便您可以进行映射以从家到远离家或远离家中获取数据。
但是当你在关键字foreignkey上设置它时,这些id将由loopback创建
{
"name": "games",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
},
"validations": [],
"relations": {
"homeTeam": {
"type": "belongsTo",
"model": "homeTeam",
"foreignKey": "homeTeamId",
"options": {
"disableInclude": false
}
},
"awayTeam": {
"type": "belongsTo",
"model": "awayTeam",
"foreignKey": "awayTeamId",
"options": {
"disableInclude": false
}
}
},
"acls": [],
"methods": {}
}
{
"name": "awayTeam",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"name": {
"type": "string"
}
},
"validations": [],
"relations": {
"games": {
"type": "hasMany",
"model": "games",
"foreignKey": "awayTeamId",
"options": {
"disableInclude": false
}
}
},
"acls": [],
"methods": {}
}
对于主场和客场模特来说也是如此 不需要设置自己的ID,它将通过使用foreignKey引用homeTeamId / awayTeamId
PS。如果您使用的是内存中的数据源,则每次更改代码并重新运行服务器时都需要放置数据。