【问题标题】:Sequelize - is it possible to limit the number of record in junction tableSequelize - 是否可以限制联结表中的记录数
【发布时间】:2021-09-18 15:38:56
【问题描述】:

有 3 个表 student_teacherstudentteacher 具有以下关系。

每个老师将负责 5 个学生,所以关系应该是 1 到 Many,但我决定创建一个联结表来存储这种关系的额外信息。

当我创建student_teacher 记录时,有效负载将是这样的:

{
  "studentId": "xxx",
  "teacherId": "yyy",
  "groupName": "Group A"
}

假设我现在在表student_teacher 中有以下记录:

[
{
    "studentId": "studentA",
    "teacherId": "teacherA",
    "groupName": "Group X"
},
{
    "studentId": "studentB",
    "teacherId": "teacherA",
    "groupName": "Group X"
},
{
    "studentId": "studentC",
    "teacherId": "teacherA",
    "groupName": "Group X"
},
{
    "studentId": "studentD",
    "teacherId": "teacherA",
    "groupName": "Group X"
},
{
    "studentId": "studentE",
    "teacherId": "teacherA",
    "groupName": "Group X"
}
]

student_teacher中已经有5条teacherA的记录,我将禁止再为teacherA创建1条记录。

是否可以在 Sequelize 中做到这一点?或者句柄我需要在node.js函数中处理?

student-teacher.model.js

const Sequelize = require('sequelize');
const DataTypes = Sequelize.DataTypes;

module.exports = function (app) {
  const sequelizeClient = app.get('sequelizeClient');
  const studentTeacher = sequelizeClient.define('student_teacher', {
    id: {
      allowNull: false,
      primaryKey: true,
      type: DataTypes.UUID,
      defaultValue: Sequelize.UUIDV4,
    },
    studentId: {
      allowNull: false,
      type: DataTypes.UUID,
      references: { model: 'student', key: 'id' },
      defaultValue: Sequelize.UUIDV4,
      unique: 'studentId_foreign_idx'
    },
    teacherId: {
      allowNull: false,
      type: DataTypes.UUID,
      references: { model: 'teacher', key: 'id' },
      defaultValue: Sequelize.UUIDV4,
      unique: 'teacherId_foreign_idx'
    },
    groupName: {
      type: DataTypes.STRING,
      allowNull: false,
      defaultValue: ''
    },
    ...
  }, {
    hooks: {
      beforeCount(options) {
        options.raw = true;
      }
    }
  });

  studentTeacher.associate = function (models) {};

  return studentTeacher;
};

student.model.js

const Sequelize = require('sequelize');
const DataTypes = Sequelize.DataTypes;

module.exports = function (app) {
  const sequelizeClient = app.get('sequelizeClient');
  const student = sequelizeClient.define('student', {
    id: {
      allowNull: false,
      primaryKey: true,
      type: DataTypes.UUID,
      defaultValue: Sequelize.UUIDV4,
    },
    email: {
      type: DataTypes.STRING,
      allowNull: false,
      isEmail: true,
      unique: 'email'
    },
    firstName:{
      type: DataTypes.STRING,
      allowNull: false,
      defaultValue: '',
    },
    lastName:{
      type: DataTypes.STRING,
      allowNull: false,
      defaultValue: '',
    }
  }, {
    hooks: {
      beforeCount(options) {
        options.raw = true;
      }
    }
  });

  student.associate = function (models) {
 student.belongsToMany(models.teacher, { as: 'teachers', through: 'student_teacher', foreignKey: 'studentId', onDelete: 'cascade' })
  };

  return student;
};

teacher.model.js

const Sequelize = require('sequelize');
const DataTypes = Sequelize.DataTypes;

module.exports = function (app) {
  const sequelizeClient = app.get('sequelizeClient');
  const teacher = sequelizeClient.define('teacher', {
    id: {
      allowNull: false,
      primaryKey: true,
      type: DataTypes.UUID,
      defaultValue: Sequelize.UUIDV4,
    },
    email: {
      type: DataTypes.STRING,
      allowNull: false,
    }
  }, {
    hooks: {
      beforeCount(options) {
        options.raw = true;
      }
    }
  });

  teacher.associate = function (models) {
 teacher.belongsToMany(models.student, { as: 'students', through: 'student_teacher', foreignKey: 'teacherId', onDelete: 'cascade' })
  };

  return teacher;
};

【问题讨论】:

    标签: mysql sql node.js sequelize.js


    【解决方案1】:

    Sequelize 的钩子非常符合您的要求:

    // in your student-teacher.model.js model (before you return the model)
    
    studentTeacher.beforeCreate(async (instance, options) => {
      try {
          const result = await studentTeacher.findAll({
              where: {
                  teacherId: instance.teacherId
              }
          });
          if(result.length === MAX_RECORDS_FOR_TEACHER) {
              throw new Error(`Cannot create more instnaces for ${instance.teacherId}`);
          }
      }
      catch(e) {
          throw e; // You must throw an error inside the hook in order to cancel 
                   // the real statement execution.
      }
    });
    

    阅读更多:https://sequelize.org/master/manual/hooks.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-18
      • 2015-10-19
      • 1970-01-01
      • 1970-01-01
      • 2011-01-28
      相关资源
      最近更新 更多