一个关于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里嵌套AuthorTag之类就会报错…已经花了好几个小时了,求指导

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解决。

0
0

Node.js+Koa2+MySQL打造前后端分离精品项目《旧岛》

理解异步编程本质/培养面向对象思维,独立完成Node.js服务端开发

2223 学习 · 878 问题

查看课程