NodeJS Sequalize Table1与Table2

时间:2017-07-27 12:41:53

标签: javascript sql node.js orm sequelize.js

我有两个表table1和table2。我想得到关系数据。我浏览了this网址,这与我的错误相同,但该解决方案对我不起作用

module.exports = function (sequelize, DataTypes) {
var table1 = sequelize.define("table1", {
    table1Id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true},
    image: {type: DataTypes.STRING},  
}, {
    timestamps: true,
    classMethods: {
        associate: function (models) {
            table1.belongsTo(models.table2, {
                onDelete: "CASCADE",
                foreignKey: {
                    name: "table2Id",
                    notEmpty: false
                }
            });
        }
    }
});
return table1;
};

另一个是:

module.exports = function (sequelize, DataTypes) {
var table2 = sequelize.define("table2", {
    table2Id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true},
    name: {type: DataTypes.STRING}, 
}, {
    timestamps: true,
    classMethods: {
        associate: function (models) {
            table2.hasMany(models.table1, {
                onDelete: "CASCADE",
                foreignKey: {
                    name: "table1Id",
                    notEmpty: false
                }
            });
        }
    }
});
return table2;
};

然后在控制器中:

models.table2.findById(req.params.id, {
        include: [{model: models.table1}] 

    }).then(function (data) {


    }).catch(Sequelize.ValidationError, function (err) {
        return res.status(422).send(err.errors);
    }).catch(function (err) {
        console.log(err.message,"err.message")
        return res.status(400).send({
            message: err.message
        });
    });

我得到的错误是Table1与Table2没有关联

1 个答案:

答案 0 :(得分:0)

如果你在续集> 4 定义关联的方式已更改。

而不是将关联定义为

const Model = sequelize.define('Model',
 { ... },
 { classMethods: { associate: function (model) {...} }
 });

现在将它们定义为

const Model = sequelize.define('Model', { ... });
 // Class Method
Model.associate = function (models) { ...associate the models };

这也可以说明为什么它似乎在一台机器而不是另一台机器上工作。