我正在使用orm sequelizeJs在我的nodeJs项目上对数据库模式进行建模。该数据库是mysql。 我有03个模型,定义如下:
// Worker model
module.exports = (sequelize, DataTypes) => {
const Worker = sequelize.define("Worker", {
workerId: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
unique: true,
allowNull: false
}
}
//Will put workerId into Order
Worker.associate = function (models) {
models.Worker.hasMany(models.Order, { foreignKey: "workerId", constraints: false });
};
//Will put workerId into Sale
Worker.associate = function (models) {
models.Worker.hasMany(models.Sale, { foreignKey: "workerId", constraints: false });
};
return Worker;
}
// Order model
module.exports = (sequelize, DataTypes) => {
const Order = sequelize.define("Order", {
orderId: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
unique: true,
allowNull: false
}
}
// Will put workerId into Order
Order.associate = function (models) {
models.Order.belongsTo(models.Worker, {
foreignKey: "workerId",
targetKey: "workerId",
constraints: false
});
};
return Order;
}
// Sale model
module.exports = (sequelize, DataTypes) => {
const Sale = sequelize.define("Sale", {
saleId: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
unique: true,
allowNull: false
}
//Will put orderId into Sale
Sale.associate = function (models) {
models.Sale.belongsTo(models.Order, { foreignKey: "orderId", constraints: false });
};
// Will put workerId into Sale
Sale.associate = function (models) {
models.Sale.belongsTo(models.Worker, { foreignKey: "workerId", constraints: false });
};
return Sale;
}
1-to-Many
和Order
之间的关联Worker
有效(workerId
被导入到Order
中)。
但是,我无法使1-to-1
和Sale
之间的关联Worker
和Order
和Sale
之间的关联同时工作。当时它是可行的。意味着我只能让orderId
或workerId
进入Sale
模型,但不能同时进入两者,这是我需要实现的。
我需要同时拥有1-to-1
和Sale & Order
之间的Sale & Worker
关系。
您能发现我可能错过或滥用的任何东西吗? 谢谢
答案 0 :(得分:0)
我发现我做错了。我正在两个具有相同名称associate
的独立函数中创建关联。我通过将关联移动到相同的函数中来修复它,如下所示:
Sale.associate = function (models) {
models.Sale.belongsTo(models.Order, { foreignKey: "orderId", constraints: false });
// Will put workerId into Sale
models.Sale.belongsTo(models.Worker, { foreignKey: "workerId", constraints: false });
};