我有两个表 table1 和 table2。我想获取关系数据。我浏览了与我的错误相同的 this URL,但该解决方案对我不起作用
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;
};
然后在 Controller 中:
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
});
});
我得到错误,表 1 与表 2 没有关联
最佳答案
如果你在 Sequelize >4
定义关联的方式发生了变化。
而不是将关联定义为
const Model = sequelize.define('Model',
{ ... },
{ classMethods: { associate: function (model) {...} }
});
它们现在被定义为
const Model = sequelize.define('Model', { ... });
// Class Method
Model.associate = function (models) { ...associate the models };
这也可以解释为什么它似乎在一台机器上工作而不是在另一台机器上工作。
关于javascript - Node JS Sequelize Table 1 与 Table2 没有关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45351136/