我有工作模式
module.exports = (sequelize, Datatypes) => {
const Jobs = sequelize.define('Jobs', {
jobinput: {
type: Datatypes.STRING
},
typeinput: {
type: Datatypes.STRING
},
jobdescinput: {
type: Datatypes.TEXT('medium')
},
locationinput: {
type: Datatypes.STRING
},
salarymininput: {
type: Datatypes.INTEGER
},
salarymaxinput: {
type: Datatypes.INTEGER
},
seniorityinput: {
type: Datatypes.STRING
},
vacancyinput: {
type: Datatypes.INTEGER
},
bountyinput: {
type: Datatypes.INTEGER
}
})
Jobs.associate = function (models) {
Jobs.belongsTo(models.User)
Jobs.belongsTo(models.Company)
Jobs.belongsToMany(models.JobSkills, { through: models.JobHasSkills, foreignKey: 'JobId' })
}
return Jobs
}
和JobSkill模型
module.exports = (sequelize, Datatypes) => {
const JobSkills = sequelize.define('JobSkills', {
skill: {
type: Datatypes.STRING,
unique: true
}
})
JobSkills.associate = function (models) {
JobSkills.belongsToMany(models.Jobs, { through: models.JobHasSkills, foreignKey: 'JobSkillId' })
}
return JobSkills
}
和多对多JobHasSkills模型
module.exports = (sequelize, Datatypes) => {
const JobHasSkills = sequelize.define('JobHasSkills', { })
JobHasSkills.associate = function (models) {
JobHasSkills.belongsTo(models.Jobs)
JobHasSkills.belongsTo(models.JobSkills)
}
return JobHasSkills
}
我正在尝试创建一个创建函数
async create (req, res) {
try {
await Jobs.create(req.body, { include: { model: JobSkills } })
.then(function (createdObjects) {
res.json(createdObjects)
})
} catch (err) {
res.status(500).send({
error: 'an error has occured while posting'
})
}
}
我通过邮递员发送的Json数据是
{ "jobinput": "Title",
"typeinput": "Part Time",
"jobdescinput": "lorem ipsum",
"locationinput": "California",
"salarymininput": "0",
"salarymaxinput": "1000",
"seniorityinput": "Internship",
"vacancyinput": "1",
"bountyinput": "10",
"skills": ["skill1","skill2","skill3" ]
}
我检查了这个答案Trying to create an instance and multiple related instances in a many to many relationship
但是我被抓住了(错误)。 这是我的第一个使用node js和sequelize的项目。有人可以帮我吗
答案 0 :(得分:0)
如果未创建表,请使用-
sequelize.define(
"Table Name"
{
Model Definations
},
{
underscored: false,// Not Required in your case
timestamps: false// Not Required in your case
}
).sync({ force: true });
一旦创建了表,请注释“同步”选项,否则在每个重新启动表上都会删除并重新创建。