【问题标题】:How to create a query in sequelize如何在 sequelize 中创建查询
【发布时间】:2021-07-20 02:38:12
【问题描述】:

我有一个课程表:

const Lesson = sequelize.define(
  'lesson',
  {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    date: { type: DataTypes.DATEONLY },
    title: { type: DataTypes.STRING },
    status: { type: DataTypes.INTEGER }
  },
  { underscored: true, timestamps: false }
);

与 Teachers 表有 belongsToMany 关系

const Teacher = sequelize.define(
  'teacher',
  {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true
    },
    name: { type: DataTypes.STRING }
  },
  { underscored: true, timestamps: false }
);

我正在尝试请求获取课程列表:

const data = await Lesson.findAll({
  include: [
    { model: Teacher, through: { attributes: [] } }
  ],
  order: [['id', 'DESC']],
  limit,
  offset
});

如何对教师人数进行限制,即只接受属于本节课的教师人数,例如,等于 3 的课。

【问题讨论】:

    标签: node.js postgresql sequelize.js


    【解决方案1】:

    您的查询将形成类似这样的内容

        const data = await Lesson.findAll({
          include: [
            { 
              model: Teacher,
              required: true
              attributes: [[Sequelize.literal('(count(teacher.id))')], 'teacherCount']
            }
          ],
          order: [['id', 'DESC']],
          having: {teacherCount: {[Op.gt]: 3}}
          limit: 10,
          offset: 0
        });
    

    这仍然是一个原始代码,您可能希望自己进行一些试验和错误,基本上您想要进行联接并从该联接中获取教师数量,一旦您想要使用它来过滤您的查询您刚刚创建的虚拟列。

    P.S:上面的代码可能会错误地抛出组,因为您需要添加 group: ['column_name'] 以便非聚合列出现在聚合查询中

    分组参考: https://www.postgresqltutorial.com/postgresql-group-by/

    最后,我建议先编写一个原始查询,然后找到方法将其转换为 sequelize,这样您就知道您面临的确切问题是什么。

    【讨论】:

      猜你喜欢
      • 2017-05-10
      • 2018-09-18
      • 2019-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      相关资源
      最近更新 更多