我有 Users
表,它与许多 Stations
相关,每个用户都与 Info
表有关系,其中包含字段 firstName
和 lastName
。我是这样抓取的:
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']);
}
在
email
或 stations
的情况下,一切正常。但是使用 info
它说没有看到和信息列。当我像这样从 join 中删除 stations
时:const notFormatedItems = await this.userRepository.findAll({
where: { role: 'user' },
include: [joinUserInfo],
paranoid: false,
order,
});
我通过
firstName
和 lastName
订购的工作正常。我做错了什么?谢谢你。Users
与 Stations
相关的 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/