gpt4 book ai didi

mysql - Sequelize 'hasMany' 关联(模型)在查询执行中的属性计数

转载 作者:行者123 更新时间:2023-11-29 01:35:12 29 4
gpt4 key购买 nike

Sequelize 版本:4.22.6,MySql版本:5.7.8我想在查询执行中'hasMany' associated(CompanyUser) 在属性中计数(在 _user_count_ 的位置)

/**
* Company user associate with Company with belongsTo relation
*/
`CompanyUser.belongsTo(Company, { foreignKey: 'company_id', targetKey: 'id'});`

/**
* Company associate with Company user with hasMany relation
*/
`Company.hasMany(CompanyUser, { foreignKey: 'company_id', sourceKey: 'id'});`

`return Company.findAll({
attributes: [
'id', 'title', 'is_enabled', '_user_count_'
]
include: [
{
model: sqConn.CompanyUser,
attributes: ['id'],
},
{
model: sqConn.CompanyLogo,
attributes:['file_object'],
}
],
}).then(function(model) {
return sequelize.Promise.resolve(model);
}).catch(function(err) {
return sequelize.Promise.reject(err);
});`

使用左连接的简单 MySQL 查询工作正常并给出计数。

最佳答案

您可以使用 sequelize.fn ,尝试运行以下查询:

Company.findAll({
attributes: [
'id', 'title', 'is_enabled',
[sequelize.fn('count', sequelize.col('company_users.id')) ,'user_count'] // <---- Here you will get the total count of user
],
include: [
{
model: sqConn.CompanyUser,
attributes: [] // <----- Make sure , this should be empty
}
],
group: ['companies.id'] // <---- You might require this one also
}).then(data => {
console.log(data); // <---- Check the output
})

关于mysql - Sequelize 'hasMany' 关联(模型)在查询执行中的属性计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52496842/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com