使用 sequelize 压平子关联中的列

Flattening columns in sub associations with sequelize

我有三个不同的表,用于保存一组用户的数据、这些组中用户的存在情况以及实际用户数据。当只拉取成员数据时,我可以将其全部展平而无需嵌套

GroupUsers.findAll({
    raw: true,
    attributes: [
        'userID',
        'userRole',
        [Sequelize.col('User.username'), 'username'],
    ],
    where: {
        groupID: 'some group id'
    },
    include: [
        {
            model: User,
            attributes: []
        }
    ],
})

哪个会 return

{
    userID: "1234",
    status: "user",
    username: "foo",
}

但是,如果我尝试通过以下方式对子关联执行相同的操作

Groups.findOne({
    where: {
        active: true,
        id: 'some group id'
    },
    include: {
        model: GroupUsers,
        attributes: [
            'userID',
            'userRole',
            [Sequelize.col('User.username'), 'username'],
        ],
        as: "members",
        include: {
            model: User,
            attributes: []
        }
    }
})

这不再有效,我收到一条错误消息,指出 members.User.username 是未知列。

尝试在带有包含的 where 子句中引用嵌套数据时会发现类似的问题,例如 with

include: {
    model: GroupUsers,
    where: {
        '$User.username$': 'foo'
    }
    ...
}

再次声明这是一个未知的列。

有谁知道是否有我遗漏的正确方法来执行此操作,或者 sequelize 只是不允许在另一个关联中引用子关联并且只允许在顶层进行这种行为?

我已经通过使用sequelize literal解决了,它有点原始但它有效但你必须知道列之前的所有关联。 在您的情况下,它将是这样的:

Groups.findOne({
  where: {
    active: true,
    id: 'some group id'
  },
  include: {
    model: GroupUsers,
    attributes: [
        'userID',
        'userRole',
        [Sequelize.literal('"members->User"."username"'), 'username'],
    ],
    as: "members",
    include: {
        model: User,
        attributes: []
    }
  }
})

像这样,您应该避免 sequelize 覆盖该属性。 当您尝试使用 where 子句时回答您的第二种情况,该子句应该在 users

include: {
    ...
    include: {
        model: User,
        attributes: [],
        where: {
           username: 'foo'
        },
        required: true
    }
  }

而不是这个:

include: {
   model: GroupUsers,
   where: {
    '$User.username$': 'foo'
   }
   ...
}