2017-10-25 4 views
0

"posts"と "comments"という2つのテーブルが定義されています。私は全ての投稿とその数のコメントをコメントタイプごとに分割したいと思っています。現在、私は、カウントを得ることができますが、コメントの種類Sequelize - 関連するデータをカウントし、列で区切る

const Sequelize = require('sequelize'); 
const sequelize = new Sequelize('postgres://[email protected]: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することはできますか?

答えて

0

生SQL何かのように:ポストでPKに

  • 変更IDをポストにFKでコメント内の列名に

    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。
  • 関連する問題