【问题标题】:Sequelize 'hasMany' associated(model) count in attributes in query executionSequelize 'hasMany' 关联(模型)计数在查询执行中的属性
【发布时间】:2019-02-28 23:58:22
【问题描述】:

续集版本: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 查询可以正常工作并给出计数。

【问题讨论】:

    标签: mysql associations sequelize.js


    【解决方案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']
      ]
    });
    

    协会:

    • 发布 M:N 类别
    • 发表 1:N 评论
    • 发布 N:1 用户

    请注意这部分是'comment.id' 而不是'comments.id'

    如果您使用'comments.id',它会为您抛出此错误:SequelizeDatabaseError: missing FROM-clause entry for table "comments"

    我的模型 - 更新: 和评论

    const { sequelize } = require('./index');
    const { Model, DataTypes } = require('sequelize');
    class CommentModel extends Model {};
    CommentModel.init({
        id: {
            primaryKey: true,
            type: DataTypes.UUID,
            defaultValue: DataTypes.UUIDV4
        },
        content: {
            type: DataTypes.TEXT,
            allowNull: false
        }
    }, {
        sequelize,
        modelName: 'comments',
        timestamps: true,
        paranoid: false
    });
    
    module.exports = CommentModel;
    

    【讨论】:

    • 您是如何设置模型的?这个解决方案对我不起作用
    • 你好@cylee。我在我的答案中添加了我的模型。你可以看到他们
    【解决方案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
    })
    

    【讨论】:

    • 出现错误:]^ SyntaxError: Unexpected token ]attributes: [ 'id','title', 'is_enabled', [ sequelize.fn('count', sequelize.col('company_users.id')) ,'user_count']], ]
    • 删除一个额外的],里面的属性,请检查更新的答案。
    • 一切正常,只有group:['companies.id']
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-09
    • 2019-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多