sequelize and postgres中关联表的多个值

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

[嗨,我正尝试在我的postgres数据库中链接步骤表和用户表

User.hasMany(models.Steps, {
  foreignKey: "stepId",
  as: "steps"
});

和步骤模型具有

Steps.belongsTo(models.User, {
  as: "user",
  foreignKey: "stepId"
});

以及我正在使用的findall中的用户服务中

include: [
{
            model: Steps,
            as: "steps",
            all: true,
            required: true
          }
        ],
        where: {
          id: req.query.id
        },
        raw: true,
        nest: true
]

这将导致以下响应

{
    "status": "success getUserById getUserById",
    "message": null,
    "data": [
        {
            "id": 5,
            "name": "rsdfsa",
            "age": 24,
            "height": "5.8",
            "weight": "40.5",
            "createdAt": "2020-03-03",
            "updatedAt": "2020-03-03",
            "steps": {
                "stepId": 5,
                "steps": "29",
                "createdAt": "2020-03-03",
                "updatedAt": "2020-03-03"
            }
        },
        {
            "id": 5,
            "name": "rsdfsa",
            "age": 24,
            "height": "5.8",
            "weight": "40.5",
            "createdAt": "2020-03-03",
            "updatedAt": "2020-03-03",
            "steps": {
                "stepId": 5,
                "steps": "34",
                "createdAt": "2020-03-03",
                "updatedAt": "2020-03-03"
            }
        }
    ]
}

是否有一种方法可以让一个用户拥有与该用户相关的所有步骤,请指导我

node.js angular postgresql sequelize.js
2个回答
0
投票

您需要使用group by子句对属于同一用户的所有步骤进行如下分组-

include: [
  {
    model: Steps,
    as: 'steps',
    all: true,
    required: true
  }
],
where: {
  id: req.query.id
},
group: ['id', '`steps`.`stepId`'],
subQuery: false

0
投票

问题是我在步骤表中没有外键,我使用stepId作为主键,但是没有userId列。一旦我更改了它,它就会起作用。

© www.soinside.com 2019 - 2024. All rights reserved.