Sequelize 'hasMany' associated(model) count in attributes in query execution

前端 未结 2 1349
滥情空心
滥情空心 2021-01-06 09:33

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

相关标签:
2条回答
  • 2021-01-06 10:03

    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
    })
    
    0 讨论(0)
  • 2021-01-06 10:05

    this is something that works for me:

    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']
      ]
    });
    

    Associations:

    • Post M:N Category
    • Post 1:N Comment
    • Post N:1 User

    please note to this part 'comment.id' not 'comments.id'.

    if you use 'comments.id' it throws this error for you: SequelizeDatabaseError: missing FROM-clause entry for table "comments"

    MY MODELS - UPDATE: and comment

    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;
    
    0 讨论(0)
提交回复
热议问题