最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Need to count a joined table rows sequelize - Stack Overflow

programmeradmin2浏览0评论

I am using sequelize to query on a sqlserver database. I have two tables:

data: columns - id, name, team, type

history:columns - id, node, date, status, data_id(foreignkey)

and a relation

history.belongsTo(data, {foreignKey: 'data_id'}

data.hasMany(history, {foreignKey: 'data_id'})

My query is:

dataModel.findAll({
    attributes: ['name'],
    include: [{
        model:historyModel
    }]
})

My result looks like this:

[
    {
         name: "1",
         history: [
             {
                 ...
             }
         ]
    },
    {
         name: "2",
         history: [
             {
                 ...
             }
         ]
    }
]`

I want that instead of the history array I will have the count of history objects in each one. The query in sql is:

select data.name, count(history.data_id) count 
from history 
inner join data on data.id=history.data_id 
group by history.data_id, data.name

I am using sequelize to query on a sqlserver database. I have two tables:

data: columns - id, name, team, type

history:columns - id, node, date, status, data_id(foreignkey)

and a relation

history.belongsTo(data, {foreignKey: 'data_id'}

data.hasMany(history, {foreignKey: 'data_id'})

My query is:

dataModel.findAll({
    attributes: ['name'],
    include: [{
        model:historyModel
    }]
})

My result looks like this:

[
    {
         name: "1",
         history: [
             {
                 ...
             }
         ]
    },
    {
         name: "2",
         history: [
             {
                 ...
             }
         ]
    }
]`

I want that instead of the history array I will have the count of history objects in each one. The query in sql is:

select data.name, count(history.data_id) count 
from history 
inner join data on data.id=history.data_id 
group by history.data_id, data.name
Share Improve this question edited Aug 30, 2018 at 9:23 Sheldore 39.1k8 gold badges62 silver badges76 bronze badges asked Aug 30, 2018 at 9:02 GandalfTheFagGandalfTheFag 531 silver badge3 bronze badges 1
  • Improved formatting – Sheldore Commented Aug 30, 2018 at 9:23
Add a ment  | 

1 Answer 1

Reset to default 8

You can do it this way:

dataModel.findAll({
    attributes: { 
        include: [[Sequelize.fn("COUNT", Sequelize.col("history.data_id")), "historyModelCount"]] 
    },
    include: [{
        model: historyModel, attributes: []
    }],
    group: ['data.id']
});
发布评论

评论列表(0)

  1. 暂无评论