Sequelize #39;hasMany#39; associated(model) count in attributes in query execution(Sequelize hasMany 关联(模型)计数在查询执行中的属性)
问题描述
续集版本:4.22.6,MySql版本:5.7.8我想在查询执行中将 'hasMany' 关联(CompanyUser)计数(在 _user_count_ 的位置)
Sequelize version: 4.22.6, MySql version:5.7.8 I want to 'hasMany' associated(CompanyUser) count in attibutes(at place of _user_count_) in query execution
/**
* 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 查询可以正常工作并给出计数.
Simple MySQL query with left-join works fine and give count.
推荐答案
你可以使用 sequelize.fn
,尝试运行下面的查询:
You can use sequelize.fn
, try to run below query :
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
})
这篇关于Sequelize 'hasMany' 关联(模型)计数在查询执行中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Sequelize 'hasMany' 关联(模型)计数在查询执行中的属性


- 更改自动增量起始编号? 2021-01-01
- SQL 临时表问题 2022-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01