使用具有相同外键的多个记录对连接表进行排序

Sequelize joining tables with multiple records with same foreign key

我有 3 个模型的续集数据库。

  1. 团队 - 主键:id
  2. 参与者 - 引用团队的外键 - teamId
  3. TeamResult- foreignKey 指的是 Team - teamId

每个团队可以有多个参与者,因此参与者 table 中可以有多个具有相同 teamId 的记录。与团队结果相同。

我正在尝试正确查询,我通过以下方式获得一个对象,其中包含与团队相关联的所有参与者和团队结果:

{
    "id": 1,
    "teamName": "Awesome Team",
    //other team attributes..


    "participants": [
        {
            "id": 12,
            "teamId": 1,
            //other details
        },
        {
            "id": 13,
            "teamId": 1,
            //other details
        },
    ],

    "teamResults": [
        {
            "id": 22,
            "teamId": 1,
            //other details
        },
        {
            "id": 13,
            "teamId": 1,
            //other details
        }
    ]
}

我写了以下声明,但我得到的只是参与者和导师中的第一个,而不是全部:

models.Team.find({
        where: {
            id: req.params.teamId
        },
        include: [
            {model: models.Participant, required: true},
            {model: models.TeamResult, required: true}
        ]
    }).then(function(team){/* handle team object here */})

我需要进行哪些更改才能获得所需的结果?

自己解决了。犯了一个愚蠢的错误。我在团队的协会中使用 hasOne 而不是 hasMany 协会。现已修复。