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

前端 未结 2 1367
滥情空心
滥情空心 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
    })
    

提交回复
热议问题