Ans*_*sud 7 mysql associations sequelize.js
Sequelize 版本:4.22.6,MySql 版本:5.7.8 我想在查询执行中在属性(在 _user_count_ 的位置)中“hasMany”关联(CompanyUser)计数
/**
* 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);
});`
Run Code Online (Sandbox Code Playgroud)
带有左连接的简单 MySQL 查询工作正常并给出计数。
Viv*_*shi 15
您可以使用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
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6337 次 |
| 最近记录: |