在内部联接中使用count来查询查询查询

时间:2017-02-26 15:26:56

标签: node.js express sequelize.js

我正在尝试将此查询转换为sequelize查询对象,这样做的正确方法是什么?

SELECT families.id, count('answers.familyId') FROM families LEFT JOIN 
answers on families.id = answers.familyId WHERE answers.isActive=1 AND
answers.answer=1 GROUP BY families.id HAVING COUNT('answers.familyId')>=6

1 个答案:

答案 0 :(得分:4)

我们假设Family是您的families续集模型,Answer是您的answers续集模型,sequelize是您的Sequelize实例

Family.findAll({
    attributes: ['*', sequelize.fn('COUNT', sequelize.col('Answers.familyId'))],
    include: [
        {
            model: Answer,
            attributes: [],
            where: {
                isActive: 1,
                answer: 1
            }
        }
    ],
    group: '"Family.id"',
    having: sequelize.where(sequelize.fn('COUNT', sequelize.col('Answers.familyId')), '>=', 6)
}).then((families) => {
    // result
});

有用的文档链接: