如何使用Sequelize Literals对嵌套模型进行排序?
解决方案
问题出在未给关联模型字段添加别名前缀,且排序数组结构需调整,同时缺少关联模型的显式引入。以下是修正后的代码:
const bookmarkedNotices = await RecruitmentNoticeBookmark.findAndCountAll({ include: [{ model: RecruitmentNotice, as: 'notice' }], // 必须显式包含关联模型 order: [ // 按状态优先级排序(active > finished > 其他) [Sequelize.literal(`CASE WHEN "notice"."status" = 'active' THEN 1 WHEN "notice"."status" = 'finished' THEN 2 ELSE 3 END`), 'ASC'], // 按关联模型的创建时间倒序 [{ model: RecruitmentNotice, as: 'notice' }, 'createdAt', 'DESC'] ] });
关键修正说明:
- 字段歧义消除:在
CASE语句中使用"notice"."status"而非status,明确指定字段来自别名notice的关联模型,避免与主表字段冲突。 - 关联模型引入:通过
include选项显式加载notice关联模型,否则Sequelize不会生成关联表的JOIN语句,导致无法访问关联字段。 - 排序结构优化:将
Sequelize.literal直接作为排序项,搭配ASC方向(确保优先级高的状态排在前面),符合Sequelize的排序语法要求。
额外验证项:
确认RecruitmentNoticeBookmark模型已正确定义关联:
// RecruitmentNoticeBookmark模型中的关联定义示例 RecruitmentNoticeBookmark.belongsTo(RecruitmentNotice, { as: 'notice', foreignKey: 'noticeId' // 替换为实际外键字段名 });
内容的提问来源于stack exchange,提问作者eungwang sim
相关产品推荐
相关产品推荐

