Sequelize一次只考虑一个关联

时间:2018-11-06 18:56:24

标签: javascript mysql node.js express sequelize.js

我正在使用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-ManyOrder之间的关联Worker有效(workerId被导入到Order中)。

但是,我无法使1-to-1Sale之间的关联WorkerOrderSale之间的关联同时工作。当时它是可行的。意味着我只能让orderIdworkerId进入Sale模型,但不能同时进入两者,这是我需要实现的。

我需要同时拥有1-to-1Sale & Order之间的Sale & Worker关系。

您能发现我可能错过或滥用的任何东西吗? 谢谢

1 个答案:

答案 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 });
    };