在查询执行中将属性“ hasMany”的关联(模型)计数序列化

时间:2018-09-25 11:13:23

标签: mysql associations sequelize.js

后续版本:4.22.6, MySql版本:5.7.8 我要在查询执行中以“有很多”关联的(CompanyUser)计入attibutes(在_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查询可以正常工作并给出计数。

2 个答案:

答案 0 :(得分:2)

您可以使用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
})

答案 1 :(得分:1)

这对我有用:

df["col3"] = df["col1"].combine_first(df["col2"])

协会:

  • 发布M:N类别
  • 帖子1:N评论
  • 发布N:1个用户

请注意await PostModel.findAll({ group: ['posts.id'], order: [['createdAt', 'DESC']], include: [ { model: CategoryModel, attributes: ['title'], where: { title: categoryTitle } }, { model: CommentModel }, { model: UserModel, attributes: ['fullname', 'id'] } ], attributes: [ 'title', 'content', 'description', 'thumbnail', 'baner', 'createdAt', 'updatedAt', [Sequelize.fn('COUNT', 'comment.id'), 'commentsCounter'] ] }); 而不是'comment.id'这部分。

如果您使用'comments.id',则会为您抛出此错误:'comments.id'

我的模型-更新: post, category, and user model 和评论

SequelizeDatabaseError: missing FROM-clause entry for table "comments"