sequelize 仅包含 returns 个结果

sequelize include returns only one result

我有一个 Users table 和一个 Groups table,当我检索单个用户时,我想获得该用户的所有组的列表属于。我创建了一个名为 GroupUsers 的连接 table,它上面有 userIdgroupId,这就是我知道用户属于某个组的方式。现在,当我尝试在 find 上使用 sequelize include 获取用户所属的组列表时,如果用户属于不同的组,它只会 returns 第一个匹配项。我该如何解决?

Users controller

return models.Users
.find({
  include: [{
    model: models.Groups,
    as: 'groups',
    limit: null,
    required: false
  }],
  where: { username }
})

Returns this:

{
    "id": 1,
    "username": "John",
    "phone": "xxxxxxxx",
    "email": "john@email.com",
    "createdAt": "2017-07-16T20:14:04.744Z",
    "updatedAt": "2017-07-16T20:14:04.744Z",
    "groups": [
        {
            "id": 1,
            "name": "Test Group",
            "type": "Public",
            "createdAt": "2017-07-16T20:13:18.392Z",
            "updatedAt": "2017-07-16T20:13:18.392Z",
            "GroupUsers": {
                "userId": 1,
                "groupId": 1,
                "last_seen": null,
                "createdAt": "2017-07-16T20:14:27.903Z",
                "updatedAt": "2017-07-16T20:14:27.903Z"
            }
        }
    ]
}

Instead of this:

    {
        "id": 1,
        "username": "John",
        "phone": "xxxxxxxx",
        "email": "john@email.com",
        "createdAt": "2017-07-16T20:14:04.744Z",
        "updatedAt": "2017-07-16T20:14:04.744Z",
        "groups": [
            {
                "id": 1,
                "name": "Test Group",
                "type": "Public",
                "createdAt": "2017-07-16T20:13:18.392Z",
                "updatedAt": "2017-07-16T20:13:18.392Z",
                "GroupUsers": {
                    "userId": 1,
                    "groupId": 1,
                    "last_seen": null,
                    "createdAt": "2017-07-16T20:14:27.903Z",
                    "updatedAt": "2017-07-16T20:14:27.903Z"
                }
            },
            {
                "id": 2,
                "name": "Test Group 2",
                "type": "Public",
                "createdAt": "2017-07-16T20:13:18.392Z",
                "updatedAt": "2017-07-16T20:13:18.392Z",
                "GroupUsers": {
                    "userId": 1,
                    "groupId": 2,
                    "last_seen": null,
                    "createdAt": "2017-07-16T20:14:27.903Z",
                    "updatedAt": "2017-07-16T20:14:27.903Z"
                }
            }
        ]
    }

我确定我在某个地方做错了我只是不知道在哪里,同样的事情也可能是 sequelize 的原因,包括结果中的连接 table:GroupUsers

看来在我的联想中,我做了:

Users.belongsToMany(models.Groups, {
  through: 'GroupUsers',
  as: 'groups',
  foreignKey: 'groupId'
});

而不是:

Users.belongsToMany(models.Groups, {
  through: 'GroupUsers',
  as: 'groups',
  foreignKey: 'userId'
});

注意 foreignKey 属性

至于同样返回的 GroupUsers 对象,我删除了它:

include: [{
    model: models.Groups,
    as: 'groups',
    attributes: ['id', 'name'],
    through: { attributes: [] }
  }]

注意 throughattributes 设置为空数组。