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

本教程将介绍Sequelize 'hasMany' 关联(模型)计数在查询执行中的属性的处理方法,这篇教程是从别的地方看到的,然后加了一些国外程序员的疑问与解答,希望能对你有所帮助,好了,下面开始学习吧。

Sequelize 'hasMany' 关联(模型)计数在查询执行中的属性 教程 第1张

问题描述

续集版本:4.22.6,MySql版本:5.7.8我想在查询执行中将 'hasMany' 关联(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
})

好了关于Sequelize 'hasMany' 关联(模型)计数在查询执行中的属性的教程就到这里就结束了,希望趣模板源码网找到的这篇技术文章能帮助到大家,更多技术教程可以在站内搜索。