0
Ich habe zwei Tabellen definiert "Beiträge" und "Kommentare". Ich möchte alle Beiträge und eine Anzahl von ganzen Kommentaren erhalten, die durch den Kommentartyp getrennt sind. Zur Zeit kann ich die Zählung, aber nicht durch Kommentartyp trennenSequelize - Count verwandte Daten und durch Spalte
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();
Ausgang wird
[
{
"id": 1,
"name": "Hello World",
"commentCount": "4"
}
]
gewünschte Ausgabe
[
{
"id": 1,
"name": "Hello World",
"commentCount": { "text": 2, "image": 1, "video": 1 }
}
]
Kann dies durch Sequelize erfolgen, oder auch roh SQL?