在查询执行中将属性中的"hasMany"关联(模型)计数序列化 [英] Sequelize 'hasMany' associated(model) count in attributes in query execution
本文介绍了在查询执行中将属性中的"hasMany"关联(模型)计数序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
后续版本:4.22.6, MySql版本:5.7.8 我要在查询执行中以有很多"关联的(CompanyUser)计数在attibutes中(在_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
})
这篇关于在查询执行中将属性中的"hasMany"关联(模型)计数序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文