【问题标题】:Column not exist in order by clause按子句的顺序不存在列
【发布时间】:2020-03-09 20:11:24
【问题描述】:

我正在使用 Sequelize 查询这样的表:

  const students = await User.findAll({
attributes: ['id', [Sequelize.literal(`"firstName" || ' ' || "lastName"`), 'name']],
where: {
  [Op.or]: [
    {
      firstName: {
        [Op.iLike]: `%${search}%`
      }
    },
    {
      lastName: {
        [Op.iLike]: `%${search}%`
      }
    },
    Sequelize.literal(`"firstName" || ' ' || "lastName" ILIKE '%${search}%'`)
  ]
},
order: Sequelize.literal(`"organization_users"."firstName" ${NATURAL_SORT} ${sort}`),
limit,
offset: limit * (page - 1),
distinct: true
});

它工作正常,但如果我包含一些模型,则“firstName”列不存在:

  const students = await User.findAll({
attributes: ['id', [Sequelize.literal(`"firstName" || ' ' || "lastName"`), 'name']],
where: {
  [Op.or]: [
    {
      firstName: {
        [Op.iLike]: `%${search}%`
      }
    },
    {
      lastName: {
        [Op.iLike]: `%${search}%`
      }
    },
    Sequelize.literal(`"firstName" || ' ' || "lastName" ILIKE '%${search}%'`)
  ]
},
include: [
  { model: ProgressGrade, as: 'student_progress_grade', required: true, where: { courseId } },
  {
    model: CourseRole,
    as: 'course_roles',
    attributes: [],
    where: { roleName: 'Student' },
    required: true
  },
  { model: Course, as: 'courses', attributes: [], where: { id: courseId }, required: true }
],
order: Sequelize.literal(`"organization_users"."firstName" ${NATURAL_SORT} ${sort}`),
limit,
offset: limit * (page - 1),
distinct: true
});

错误信息:

错误:SequelizeDatabaseError:列 organization_users.firstName 不存在

这是我第一次遇到这个问题,我做了很多搜索但没有希望。有人知道 Sequelize 在这里的工作原理吗?

我正在使用在 Nodejs 13.8.0、PostgreSQL 10.12 上运行的 Sequelize 5.21.5

【问题讨论】:

  • 请在此处分享确切的错误

标签: node.js sequelize.js


【解决方案1】:

请将subQuery属性设置为false,如下-

 const students = await User.findAll({
attributes: ['id', [Sequelize.literal(`"firstName" || ' ' || "lastName"`), 'name']],
where: {
  [Op.or]: [
    {
      firstName: {
        [Op.iLike]: `%${search}%`
      }
    },
    {
      lastName: {
        [Op.iLike]: `%${search}%`
      }
    },
    Sequelize.literal(`"firstName" || ' ' || "lastName" ILIKE '%${search}%'`)
  ]
},
include: [
  { model: ProgressGrade, as: 'student_progress_grade', required: true, where: { courseId } },
  {
    model: CourseRole,
    as: 'course_roles',
    attributes: [],
    where: { roleName: 'Student' },
    required: true
  },
  { model: Course, as: 'courses', attributes: [], where: { id: courseId }, required: true }
],
order: Sequelize.literal(`"organization_users"."firstName" ${NATURAL_SORT} ${sort}`),
limit,
offset: limit * (page - 1),
distinct: true,
subQuery: false
});

希望对你有帮助!

【讨论】:

  • 能否请您发布Sequelize生成的先前查询及其输出和修改后生成的查询以及各自的输出?这将有助于理解问题
  • 我通过将“firstName”添加到属性列表中找到了解决方法
  • @NguyenHoangVu-K11FUGHCM,很高兴知道这一点!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-10
  • 1970-01-01
  • 2015-04-22
  • 2021-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多