首页 文章

Loopback中与同一类的多个关系

提问于
浏览
0

我试图了解关系如何在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是正确的 .

我在这做错了什么?

1 回答

  • 0

    在游戏中,您不需要为其ID设置属性 . loopback将自动创建自动增量ID . 游戏表应该保留TeamId和homeTeamId,以便您可以进行映射以获取数据从家到外或远离家 .
    但是当你在关键字foreignkey上设置它时,这些id将由loopback创建

    games.model

    {
      "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 . 如果您使用的是内存中的数据源,则每次更改代码并重新运行服务器时都需要放置数据 .

相关问题