node.js - 如何在 NodeJS Sequelize 中按查询计算组

标签 node.js postgresql sequelize.js

在 Rails 中,我可以执行一个简单的 ORM 查询来查询模型拥有的点赞数:

    @records = Model
        .select( 'model.*' )
        .select( 'count(likes.*) as likes_count' )
        .joins( 'LEFT JOIN likes ON model.id = likes.model_id' )
        .group( 'model.id' )

这会生成查询:

SELECT  models.*, count(likes.*) as likes_count
FROM "models" JOIN likes ON models.id = likes.model_id
GROUP BY models.id

在 Node Sequelize 中,任何类似的尝试都会失败:

return Model.findAll({
    group: [ '"Model".id' ],
    attributes: ['id', [Sequelize.fn('count', Sequelize.col('"Likes".id')), 'likes_count']],
    include: [{ attributes: [], model: Like }],
});

这会生成查询:

SELECT
    Model.id,
    count(Likes.id) AS likes_count,
    Likes.id AS Likes.id           # Bad!
FROM Models AS Model
LEFT OUTER JOIN Likes
    AS Likes
    ON Model.id = Likes.model_id
GROUP BY Model.id;

哪个会产生错误:

column "Likes.id" must appear in the GROUP BY clause or be used in an aggregate function

它错误地选择了likes.id,我不知道为什么,也不知道如何摆脱它。

最佳答案

This sequelize github issue看起来完全像你的情况:

User.findAll({
  attributes: ['User.*', 'Post.*', [sequelize.fn('COUNT', 'Post.id'), 'PostCount']],
  include: [Post]
});

关于node.js - 如何在 NodeJS Sequelize 中按查询计算组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29869077/

相关文章:

PostgreSQL:内部加入特定值

javascript - 使用 Sequelize 根据请求正文中的项目数创建动态 where 子句?

javascript - 如何使用 Material-ui 为 React Next 应用程序添加 CSS 服务器端渲染

node.js - nowjs 不工作

node.js - 我可以在 'require' 中使用 'import' 而不是 'fb react-create-app' 吗?

javascript - 类型错误 : defineCall is not a function. require() 失败

amazon-web-services - AWS Lambda 函数无法从 EC2 实例 : SequelizeConnectionError connect ETIMEDOUT 访问 MySQL 数据库

javascript - 如何避免在node.js中使用模块?

sql - 在 case 语句中使用 select 语句中的参数

postgresql - 如何在 group by 子句后应用 case when 语句