Sequelize - 计算相关数据并按列分开

时间:2017-10-25 14:23:45

标签: sql sequelize.js

我有两个表定义了“帖子”和“评论”。我希望得到所有帖子和一些总评论,按评论类型分开。目前我可以获得计数,但不能通过评论类型分开

const Sequelize = require('sequelize');
const sequelize = new Sequelize('postgres://username@localhost:5432/test');

const posts = sequelize.define('posts', {
  name: Sequelize.STRING,
})

const comments = sequelize.define('comments', {
  title: Sequelize.STRING,
  type: Sequelize.STRING
})

posts.hasMany(comments);
comments.belongsTo(posts);

const importData = async () => {
  // Insert test data
  await sequelize.sync({ force: true });
  await posts.create({ id: 1, name: 'Hello World' })
  await comments.create({ postId: 1, title: 'This is great', type: 'text' })
  await comments.create({ postId: 1, title: 'Thanks', type: 'text' })
  await comments.create({ postId: 1, title: 'Oh Yeah', type: 'image' })
  await comments.create({ postId: 1, title: 'Oh Yeah', type: 'video' })

  // Fetch data
  const post = await posts.findAll({
    where: { id: 1 },
    attributes: ['id', 'name', [sequelize.fn('COUNT', 'comments.id'), 'commentCount']],
    include: [{ model: comments, attributes: [] }],
    group: ['posts.id']
  })
  console.log(JSON.stringify(post, null, 4))
}

importData();

输出

[
    {
        "id": 1,
        "name": "Hello World",
        "commentCount": "4"
    }
]

期望输出

[
    {
        "id": 1,
        "name": "Hello World",
        "commentCount": { "text": 2, "image": 1, "video": 1 }
    }
]

这可以通过Sequelize,甚至原始SQL来完成吗?

1 个答案:

答案 0 :(得分:0)

Raw SQL类似于:

SELECT P.ID, C.Comment_Count, C.Type 
FROM POSTS P
LEFT JOIN (SELECT count(*) Comment_Count, PostID, type
           FROM Comments 
           GROUP BY POSTID, type) C
 on P.ID = C.PostID  

更改

  1. PostID到评论中的列名称,即发布的FK
  2. 在帖子中将ID更改为PK。