【发布时间】:2020-09-21 23:42:50
【问题描述】:
我是 sequelize 的新手,我正在尝试创建两个表。用户和项目。我为每个名为 UserModel 和 ProjectModel 的模型定义了一个模型,当我尝试将项目与用户关联时,我遇到了这个错误:
belongsTo 调用的东西不是 Sequelize.Model
这些是我定义每个模型的文件:
user.js
module.exports = (sequelize, DataType) => {
const UserModel = sequelize.define("user", {
id: {
type: DataType.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false,
},
email: {
type: DataType.STRING,
allowNull: false,
isEmail: {
msg: "The format of the e-mail is not correct"
},
validate: {
notNull: {
msg: "E-mail cannot be empty"
}
}
},
name: {
type: DataType.STRING,
is: /^[a-zA-Z ]+$/i,
allowNull: false,
validate: {
notNull: {
msg: "Name cannot be empty"
}
}
},
surname: {
type: DataType.STRING,
is: /^[a-zA-Z ]+$/i,
allowNull: false,
validate: {
notNull: {
msg: "Surname cannot be empty"
}
}
}
});
UserModel.associate = (models) => {
UserModel.hasMany(models.ProjectModel, {
foreignKey: "userID"
})
}
return UserModel;
};
project.js
module.exports = (sequelize, DataType) => {
const ProjectModel = sequelize.define("project", {
id: {
type: DataType.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false,
},
name: {
type: DataType.STRING,
is: /^[a-zA-Z ]+$/i,
allowNull: false,
validate: {
notNull: {
msg: "Name cannot be empty"
}
}
},
body: {
type: DataType.TEXT,
allowNull: false,
validate: {
notNull: {
msg: "Body cannot be empty"
}
}
},
status: {
type: DataType.ENUM("active", "inactive", "declined", "completed"),
allowNull: false,
validate: {
notNull: {
msg: "Status cannot be empty"
}
}
},
userID: {
type: DataType.INTEGER,
allowNull: false,
validate: {
notNull: {
msg: "userID cannot be empty"
}
},
references: {
model: UserModel,
key: "id"
}
}
});
ProjectModel.associate = (models) => {
ProjectModel.belongsTo(models.UserModel, {
foreignKey: "userID"
});
}
ProjectModel.belongsTo(UserModel, {
foreignKey: "userID"
});
return ProjectModel;
}
我做错了什么?
【问题讨论】:
标签: node.js sequelize.js