mysql - Sequelize 多连接中的排序错误

标签 mysql node.js sequelize.js

我有 Users 表,它与许多 Stations 相关,每个用户都与 Info 表有关系,其中包含字段 firstNamelastName 。我是这样抓取的:

const joinUserInfo: any = {
  model: userInfoModel,
  where: { deletedAt: null },
  required: true,
};
const joinStations = {
  model: stationModel,
  required: true,
};
const notFormatedItems = await this.userRepository.findAll({
  where: { role: 'user' },
  include: [joinUserInfo, joinStations],
  paranoid: false,
  order,
});

比我有一种构建 order 的方法。它看起来像这样:
private createAdminsListOrdering(query) {
  const validOrderingItems = [];
  if (query.fullName) {
    validOrderingItems.push(['info', 'lastName', query.fullName]);
    validOrderingItems.push(['info', 'firstName', query.fullName]);
  }
  if (query.email) {
    validOrderingItems.push(['email', query.email]);
  }
  if (query.station) {
    validOrderingItems.push(['stations', 'name', query.station]);
  }

  return validOrderingItems.push(['createdAt', 'DESC']);
}

emailstations 的情况下,一切正常。但是使用 info 它说没有看到和信息列。当我像这样从 join 中删除 stations 时:
const notFormatedItems = await this.userRepository.findAll({
  where: { role: 'user' },
  include: [joinUserInfo],
  paranoid: false,
  order,
});

我通过 firstNamelastName 订购的工作正常。我做错了什么?谢谢你。
UsersStations 相关的 many-to-many :
  @BelongsToMany(
    () => stationModel,
    () => userStationModel,
  )
  stations?: stationModel[];

最佳答案

问题出在分页...我使用自定义函数来创建分页:

export const paginatedQuery = ({ page = 0, pageSize = 0 }) => {
  if (!pageSize) {
    return {};
  }
  const limit = pageSize;
  const offset = page * pageSize;

  return { offset, limit };
};

我的要求是:
const notFormatedItems = await this.userRepository.findAll({
  where: { role: 'user' },
  include: [joinUserInfo, joinStations],
  paranoid: false,
  order,
  ...paginatedQuery(query),
});

而且,当我使用 logging 调试请求时,我注意到我的 Info 表在子查询中。然后我开始在 sequelize 中搜索子查询并找到标志 subQuery ,强制不使用子查询。在此之后,我的请求工作正常:
const notFormatedItems = await this.userRepository.findAll({
  where: { role: 'user' },
  include: [joinUserInfo, joinStations],
  paranoid: false,
  order,
  ...paginatedQuery(query),
  subQuery: false,
});

希望它会帮助某人。

关于mysql - Sequelize 多连接中的排序错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60478504/

相关文章:

Mysql 插入时丢失 11 条记录

c++ - 如何修复: "MySQL_Prepared_ResultSet::getInt: invalid value of ' columnIndex"

mysql - 如何修复错误 "Cannot resolve column..."

Node.js:分块传输编码

node.js - 在 Sequelize 中引用同一模型的多个外键属性时出错

javascript - NodeJS : Create api that will manage to generate the for loop as dynamic based on key value

php - 如何从Mysql获取两个特定日期之间的数据

ruby-on-rails - Rails 和 Socket.io (node.js)

javascript - 从数组动态创建Json文件

node.js - 当真正的 sequelize 连接在 require 树中时,为什么这个 sequelize-test-helper 调用不起作用?