我有两个型号User
和Role
。这两个型号具有many-to-many
连接。所以,我创建了第三个模型——UserRole
。
问题是,在这个查询中,这个UserRole
也包括在内。
async getUser(conditionals: object) {
return await this.userRepository.findOne({
where: { ...conditionals },
include: [{ model: Role, attributes: 'value' } ]
});
}
响应示例(不要注意格式,数据是从jwt
编码和解码的(:
{
"userId": "7a145aea-72c8-4b96-a25b-b404f9b1bf5a",
"username": "bl4drnnr",
"roles": [
{
"value": "USER",
"UserRole": {
"id": "e9d2afe8-ddd1-4311-ab14-6638b79d0d80",
"userId": "7a145aea-72c8-4b96-a25b-b404f9b1bf5a",
"roleId": "123e4567-e89b-12d3-a456-426614174001"
}
}
],
"type": "access",
"iat": 1659878703,
"exp": 1659879603
}
正如你已经得到的,我想做的是排除这个UserRole
模型,并使其看起来像这样:
{
"userId": "7a145aea-72c8-4b96-a25b-b404f9b1bf5a",
"username": "bl4drnnr",
"roles": [ { "value": "USER" } ],
"type": "access",
"iat": 1659878703,
"exp": 1659879603
}
我试图使用exclude
作为sequelize属性,但它似乎只适用于字段,而不适用于模型。那么,我如何从数据库请求中排除这个UserRole
模型呢?
您可以使用through
和空的attributes
:数组
async getUser(conditionals: object) {
return await this.userRepository.findOne({
where: { ...conditionals },
include: [
{
model: Role,
attributes: ['value'],
through: {
attributes: []
}
}
]
});
}