一个关于sequelize多对多查询的问题
来源:15-6 现代大型Web架构讲解

西麦
2019-07-14
const { rows, count } = await Article.findAndCountAll({
where,
distinct: true,
offset: start * pageCount,
limit: pageCount,
order: [
['created_date', 'DESC']
],
include: [
{
model: Author,
attributes: ['id', 'name', 'avatar'],
as: 'authors'
},
{
model: Tag,
as: 'tags'
},
{
model: Category,
attributes: ['id', 'name'],
as: 'category',
},
{
model: Comment,
as: 'comments',
attributes: ['id']
},
]
})
我想在查询的时候给文章列表添加多一个comment_count
的字段来记录评论数量,而不保留comments
字段,比如返回:
[
{
id: 0,
category: {
id: 1,
name: 'category'
},
authors: [],
tags: [],
comment_count: 10,
...
},
...
]
我google了很久,找到以下方法,但是只能在include
里只有一个comments
时才有用。一旦在include
里嵌套Author
、Tag
之类就会报错…已经花了好几个小时了,求指导
Location.findAll({
attributes: {
include: [[Sequelize.fn('COUNT', Sequelize.col('comments.id')), 'comment_count']]
},
include: [{
model: Comment, as: 'comments', attributes: []
}],
group: ['Article.id']
})
写回答
1回答
-
7七月
2019-07-16
别折腾了。这个其实建议单表查询,或者写SQL。很多大厂都是禁止使用Join的,复杂的东西就用单表多次查询或者写SQL解决。
00
相似问题