mysql - Sequelize with koa2 不能限制记录。我能怎么做?

标签 mysql sequelize.js koa2

async function selectCards ({
  status,
  teamId,
  userId,
  GMTTime,
  cardId,
  page,
  pageSize
}) {
  console.log(page, pageSize)
  const teamWhere = {}
  if (teamId) {
    teamWhere.id = teamId
  }
  const cardWhere = {}
  if (GMTTime) {
    cardWhere.startAt = {
      [Op.lt]: GMTTime
    }
  }
  if (cardId) {
    cardWhere.id = cardId
  }
  const userCardWhere = {
    userId
  }
  if (status) {
    userCardWhere.status = status
  }
  const result = await User.findOne({
    where: {
      id: userId
    },
    attributes: [],
    include: {
      model: Card,
      where: cardWhere,
      through: {
        where: userCardWhere
      },
      include: {
        model: Team,
        where: teamWhere,
        include: UserTeam
      }

      limit: pageSize // while it cause an error
    }
  })
  if (result == null) return { rows: [] }
  result.cards.map(card => {
    card.dataValues.status = card.user_card.status
    delete card.dataValues.user_card
    card.dataValues.team.dataValues.isAdmin = card.team.user_teams[0].isAdmin
    delete card.dataValues.team.dataValues.user_teams
    return card
  })
  return result
}

当我尝试添加上述限制时
发生了错误
Only HasMany associations support include.separate Error: Only HasMany associations support include.separate

而一张卡会有很多用户,而一个用户可能有很多卡
这是一个“m:n”协会

当我尝试使用

order: [['startAt', 'desc']]

它也不起作用

所以我需要用更多的代码来限制它

  result.cards.sort((card1, card2) => (
    card2.startAt - card1.startAt
  ))
  const ret = result.cards.slice((page - 1) * pageSize, page * pageSize)
  return { rows: ret }

使用更多的代码不是一个好的选择,因为当数据太大时,它需要 O(nlogn) 来做
我可以通过 Sequelize 找到一些解决方案吗?

顺便说一句,这是下面的模型关联

Team.hasMany(Card, {
  onDelete: 'CASCADE'
})
Card.hasOne(User, {
  onDelete: 'CASCADE',
  foreignKey: 'publishId'
})
Card.belongsTo(Team, {
  onDelete: 'CASCADE'
})

Card.belongsToMany(User, { through: UserCard })
User.belongsToMany(Card, { through: UserCard })
User.hasMany(UserCard)
UserCard.belongsTo(User)
Card.hasMany(UserCard)
UserCard.belongsTo(Card)

最佳答案

您不能在包含多对多关联的父记录上使用 limit(尤其是在此包含中使用 where)。这来自 SQL。如果您加入父表和子表,然后以这种方式添加 limit,您将获得前 N 条混合父子记录,而不是前 N 条父记录与所有子记录。是的,您可以尝试简单的 SQL 查询,您将获得所需的结果,但 Sequelize 无法为您构建此类查询。
但是,您可以尝试使用 sequelize.literal (以及像 (EXISTS (SELECT 1 FROM CHILD_TABLE WHERE PARENT_ID=PARENT_TABLE.ID))这样的 SQL 子查询来获取带有子查询的父记录,以通过某些条件的子记录的存在来过滤它们。在这种情况下,您无法在同一查询中获取此子记录,但可以正确使用 limit。然后您可以使用父记录的 id 列表分别获取所有子记录。

关于mysql - Sequelize with koa2 不能限制记录。我能怎么做?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62146058/

相关文章:

php - 为第一个 JSON PHP 添加值

jquery - 使用 InstantEdit 2.0 JS 内联编辑 mysql 数据

node.js - 如何在 sequelize 连接对象中设置应用程序名称?

node.js - "defineCall is not a function"。在 Node.JS 中使用 sequelize

javascript - Koa.js中的route()不是一个函数

node.js - 从中间件传递值到 Koa 2 中查看

node.js - 在连接字符串密码字段中使用 Promise 返回数据库未连接

mysql - 如何使用etl工具将excel表转换成mysql数据库

php - 如何在不删除 php 和 mysql 中旧记录的情况下更新记录?

javascript - Sequelize.js findAll 与包含搜索外键使页面永远不会加载