使用 sequelize,我们无法执行包含来自其他模型(播放器)的字段而不包含模型名称作为属性的查询。
我们想获得这个结果(查看每个对象的最后一个属性:数字):
[ { id: '35',
username: '4f224bd78d1a943ead9db2f73991e93dc8227335',
firstName: '8c81f070b9adad3d3693',
lastName: 'f9f5792d8a827e83974b',
email: 'd6fd38bb112da3a55b23@3c1f780dea427bc097ab.com',
created_at: '2017-03-16T07:35:15.676Z',
updated_at: '2017-03-16T07:35:15.676Z',
deleted_at: null,
number: null },
{ id: '36',
username: '613400c032540519fce322f4aa6abdb082834005',
firstName: '8bbc5692042ea4ce06f6',
lastName: 'b26d6701c275e07e1ea1',
email: '59e8d5b35185810a31e5@41677c1723806c2afac0.com',
created_at: '2017-03-16T07:35:15.768Z',
updated_at: '2017-03-16T07:35:15.768Z',
deleted_at: null,
number: 10 } ]
相反,我们得到了这个:
[ { id: '35',
username: '4f224bd78d1a943ead9db2f73991e93dc8227335',
firstName: '8c81f070b9adad3d3693',
lastName: 'f9f5792d8a827e83974b',
email: 'd6fd38bb112da3a55b23@3c1f780dea427bc097ab.com',
created_at: '2017-03-16T07:35:15.676Z',
updated_at: '2017-03-16T07:35:15.676Z',
deleted_at: null,
Player: { number: null } },
{ id: '36',
username: '613400c032540519fce322f4aa6abdb082834005',
firstName: '8bbc5692042ea4ce06f6',
lastName: 'b26d6701c275e07e1ea1',
email: '59e8d5b35185810a31e5@41677c1723806c2afac0.com',
created_at: '2017-03-16T07:35:15.768Z',
updated_at: '2017-03-16T07:35:15.768Z',
deleted_at: null,
Player: { number: 10 } } ]
我们涉及到 4 个模型:User(拥有几乎所有的属性)、Player(拥有数字)、Role(包含角色)和 UserRole(关联用户和角色)。
async function getPlayers() {
const playerRole = await sequelize.models.Role.getPlayerRole();
return sequelize.models.User.findAll({
include: [{
association: sequelize.models.User.hasOne(sequelize.models.UserRole),
model: sequelize.models.UserRole,
where: {
club_id: this.clubId,
team_id: this.id,
role_id: playerRole.id
}
}, {
association: sequelize.models.User.hasOne(sequelize.models.Player),
model: sequelize.models.Player,
where: {
team_id: this.id,
},
attributes: ['number']
}]
});
}
最佳答案
您可以使用 sequelize.col()
,但您可能应该将 raw: true
添加到 findAll
调用中,否则结果将被转换为 User
模型实例,因此无论如何都会忽略 number
属性。
return sequelize.models.User.findAll({
attributes: { include: sequelize.col('Player.number') },
raw: true, // added to prevent returning User instances from the query, only simple JSON data
include: [
{
model: sequelize.models.UserRole,
where: {
club_id: this.clubId,
team_id: this.id,
role_id: playerRole.id
}
},
{
model: sequelize.models.Player,
where: {
team_id: this.id,
},
attributes: []
}
]
});
我已经删除了
association
属性 - 我假设您已经在模型定义中声明了它们,因此在进行查询时不需要每次都使用它们。必须在 Sequelize 实例上调用
col()
方法。
关于sequelize.js - 无法删除 Sequelize 查询中的模型属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42829071/