Sequelize在带include的时候findAndCountAll查询的count错误问题
发布于 1 年前 作者 vitozyf 1607 次浏览 来自 分享

如下,Sequelize查询的数据表只有14条数据,但查询结果是36,只要不加include条件就是正确的14,是带上了include中的Comments表的数据,求解

let query = {}
  if (where) {
    query = Object.assign({}, query, where)
  }

  let findQuery = {
    where: query,
    include: [
      {
        model: Comments,
        attributes: [
          'Id'
        ]
      }
    ],
    attributes: [
        'EditAt',
        'CreatedAt',
        'CreatedAtStr',
        'Id',
        'Plate',
        'TopicContent',
        'TopicHits',
        'TopicReplies',
        'TopicLabel',
        'TopicName',
        'UserId'
    ],
    order: [
      ['EditAt', 'DESC'],
      ['createdAt', 'DESC']
    ]
  }

  if (pg) {
    findQuery = Object.assign({}, findQuery, {
      offset: pg.offset,
      limit: pg.limit
    })
  }
  Topics.findAndCountAll(findQuery).then(res => {
    cb(null, res);
    console.log(res.count)
    return null;
  }).catch(err => {
    LoggerErr.error(err)
    cb(err)
  })
4 回复

findAllandCount({ include:[], where:{}, distinct:true //这一句可以去重,主表是14条,count就是14 })

楼上正解,options中 distinct: true

@gzx1996 谢谢,明白了

回到顶部