Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
646 views
in Technique[技术] by (71.8m points)

求助 ,sequelize怎么查询关联子表的数量

如题 有ModelA ModelB两个表 ModelA.hasMany(ModelB)

ModelA.findAll({
    where:{
        //....
    },
    include:[
        {
            model:ModelB
        }
    ]
})

我想查询ModelB有多少个符合条件的个数 请问需要怎么做

by the way : 不需要ModelB的数据,只需要统计个数


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

attributes 里面可以写sql查询语句!

ModelA.findAll({
    attributes: [
    'id',
    'name',
    [Sequelize.literal(`(
            SELECT COUNT(*)
            FROM tableB AS tableB
            WHERE
                tableB.foreign_id = tableA.id
        )`),
      'count']
    ],
    where:{
     //....
    },
})

result

[
{id: '',name: '',count: ''},
{id: '',name: '',count: ''},
]

不知道这样是否能满足你的查询需求!
参考链接 Sub Queries


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...