根据不同模型中的其他列验证一个模型的“sequelize”列

问题描述 投票:0回答:1

我有两个模型,假设“Person”有名字、姓氏列。 第二个是“学生”,它具有其他属性。 我想验证如果创建了新学生,则“first_name”不为空。 但我想在定义模型时这样做。这可能吗?

const Student = sequelize.define("student", {
    id: {
      allowNull: false,
      primaryKey: true,
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      validate: {
        isValid() {
          //here I want to validate if Person.first_name is not null, and if it is I want to throw new Error.
        }
      }
    },
}

感谢您的帮助。

javascript node.js sequelize.js psql
1个回答
0
投票

如果有人仍在寻找此解决方案

const Student = sequelize.define("student", {
    id: {
      allowNull: false,
      primaryKey: true,
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      validate: {
        isValid(curVal, next) {
          sequelize.models.Person <--- your other table model
          .findOne({ where: { col1: curVal } }) <--- add where clause as you need
          .then((result) => {
            if (!result) {
              throw new Error('Invalid Person!');
            }
            return next();
          })
          .catch(function (err) {
            return next(err);
          });
        }
      }
    },
}
© www.soinside.com 2019 - 2024. All rights reserved.