[英]table association not created One-To-Many sequelize node
我正在为我的数据库创建关联。 但她并没有创建所有的关联,例如,她没有将合同与工资单联系起来。 我尝试了数据库中的选项,但它们没有帮助。 告诉我我可以尝试做什么以及我做错了什么?
创建关联
db.Contracts.hasMany(db.Payrolls, {
foreignKey: {
name: 'contract_id',
sourceKey: 'id',
}
})
db.Payrolls.belongsTo(db.Contracts, {
foreignKey: {
name: 'contract_id',
targetKey: 'id',
}
})
创建合约
module.exports = (sequelize, DataTypes) => {
const Contracts = sequelize.define("Contracts", {
id: {
type: DataTypes.STRING,
allowNull: false,
primaryKey: true,
autoIncrement: false
},
month_pay: {
type: DataTypes.INTEGER,
allowNull: false
}
}, { timestamps: false });
return Contracts;
};
创建工资单
module.exports = (sequelize, DataTypes) => {
const Payrolls = sequelize.define("Payrolls", {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
allowNull: false,
autoIncrement: true
},
pay_date: {
type: DataTypes.DATE,
allowNull: false,
},
amount: {
type: DataTypes.INTEGER,
allowNull: false
}
}, { timestamps: false });
return Payrolls
};
例如工作协会:
module.exports = (db) => {
//#region One-To-Many Contracts->Courses
db.Courses.hasMany(db.Contracts, {
foreignKey: {
name: 'course_name',
sourceKey: 'name',
primaryKey: true,
}
})
db.Contracts.belongsTo(db.Courses, {
foreignKey: {
name: 'course_name',
targetKey: 'name',
primaryKey: true,
}
})
//#endregion
//#region One-To-Many Contracts->Pupils
db.Pupils.hasMany(db.Contracts, {
foreignKey: {
name: 'pupil_id',
sourceKey: 'id',
primaryKey: true,
}
})
db.Contracts.belongsTo(db.Pupils, {
foreignKey: {
name: 'pupil_id',
targetKey: 'id',
primaryKey: true,
}
})
//#endregion
//#region One-To-Many Payrolls->Contracts
db.Contracts.hasMany(db.Payrolls, {
foreignKey: {
name: 'contract_id',
sourceKey: 'id',
}
})
db.Payrolls.belongsTo(db.Contracts, {
foreignKey: {
name: 'contract_id',
targetKey: 'id',
}
})
//#endregion
return db
}
查看 hasMany 和 belongsTo 的 Sequelize v7 文档
https://sequelize.org/api/v7/classes/model#hasMany
https://sequelize.org/api/v7/classes/model#belongsTo
您传递给 foreignKey 对象的那些 sourceKey 和 targetKey 属性似乎应该是它们在选项对象中的属性,而不是嵌套在 foreignKey 中。
您在Contracts
和Payrolls
中有不兼容的主键类型:
合约
id: {
type: DataTypes.STRING,
allowNull: false,
primaryKey: true,
autoIncrement: false
},
工资单
id: {
type: DataTypes.INTEGER,
primaryKey: true,
allowNull: false,
autoIncrement: true
},
所以 DB 会抛出你没有捕获到的错误。 添加.catch
看看:
sequelize.sync({alter: false, force: true}).then(async () => {
app.listen(PORT, () => {
console.log(`http://localhost:${PORT}`);
})
}).catch((err) => {
console.error(err)
})
您还需要修复其他关联,这些关联使用Contacts
从主键中排除id
以外的字段
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.