我想知道当某些顺序标准来自主模型与另一个模型之间的连接结果的列时,如何在 Sequelize
order
方法中应用 findAndCountAll
参数。这些模型对应于 PostgreSQL 表。
例如,此代码建立了订购标准。当我想按另一个型号的特定列订购时,我使用:
[col('model2.year'), 'ASC']
。
export enum ORDER_BY_ENUM {
HIGHER_PRICE,
LOWER_PRICE,
RECENT_YEAR,
OLDEST_YEAR,
MOST_POPULAR,
}
const buildOrderCriteria = (
orderBy: ORDER_BY_ENUM,
publicationOrderBy: any[],
) => {
let order = null;
if (orderBy) {
order = ORDER_BY_ENUM[orderBy];
if (order === undefined) {
const message = 'Ordering type does not exist';
throw new Error(message);
}
} else {
order = ORDER_BY_ENUM.LOWER_PRICE;
}
if (order >= 0) {
switch (order) {
case ORDER_BY_ENUM.HIGHER_PRICE:
publicationOrderBy.push(['price', 'DESC']);
return { publicationOrderBy, order };
case ORDER_BY_ENUM.LOWER_PRICE:
publicationOrderBy.push(['price', 'ASC']);
return { publicationOrderBy, order };
case ORDER_BY_ENUM.RECENT_YEAR:
publicationOrderBy.push([col('model2.year'), 'DESC']);
return { publicationOrderBy, order };
case ORDER_BY_ENUM.OLDEST_YEAR:
publicationOrderBy.push([col('model2.year'), 'ASC']);
return { publicationOrderBy, order };
case ORDER_BY_ENUM.MOST_POPULAR:
publicationOrderBy.push(['views', 'ASC']);
return { publicationOrderBy, order };
default:
// eslint-disable-next-line no-console
console.log(`Sorting type ${order} is not defined`);
break;
}
}
};
// when using the above method
const publicationOrderBy = [];
const orderCriteria = buildOrderCriteria(
orderBy,
publicationOrderBy,
);
const publications = await Publication.findAndCountAll({
where: someCondition,
include: [
{
model: Model2,
where: model2WhereCondition,
include: [{
model: Model3,
include: [{
model: Model4,
where: model4WhereCondition,
attributes: ['something'],
}],
}],
},
{
model: Model5,
where: model5WhereCondition,
},
],
limit: size,
offset,
logging: true,
order: orderCriteria.publicationOrderBy,
});
问题在于,当订单来自另一个模型的列时,它无法正确排序。它会抛出如下错误:
missing FROM-clause entry for table "model2"
希望任何人都可以就此事提供任何帮助。预先感谢。
问题的原因是,当您在查询的 order 子句中使用 col('model2.year') 时,Sequelize 不会自动创建在查询中包含 Model2 表所需的 SQL JOIN 语句。您必须确保 Sequelize 在 SQL 查询中为 Model2 创建 JOIN 语句才能解决此问题。这可以通过在 Model2 include 选项中指定必要的关系来完成。您应该特别包含从主模型到模型 2 的关联。
这是您的代码的更新版本:
const publications = await Publication.findAndCountAll({
where: someCondition,
include: [
{
model: Model2,
where: model2WhereCondition,
include: [
{
model: Model3,
include: [
{
model: Model4,
where: model4WhereCondition,
attributes: ['something'],
},
],
},
],
},
{
model: Model5,
where: model5WhereCondition,
},
],
limit: size,
offset,
logging: true,
order: orderCriteria.publicationOrderBy,
});
希望它有效:)