Mysql 在两个模型上使用hasMany继续处理急负荷错误
我有两个模型(Course和Company),它们作为外键关联到日志模型中。我能够在日志模型的查询中包含/加入课程模型,而不会出现问题,但是公司模型总是抛出一个Sequelize加载错误 我曾尝试在hasMany和belongsTo协会上使用“as:companys”,但没有奏效。我也尝试过重新排序,但没有成功Mysql 在两个模型上使用hasMany继续处理急负荷错误,mysql,node.js,sequelize.js,Mysql,Node.js,Sequelize.js,我有两个模型(Course和Company),它们作为外键关联到日志模型中。我能够在日志模型的查询中包含/加入课程模型,而不会出现问题,但是公司模型总是抛出一个Sequelize加载错误 我曾尝试在hasMany和belongsTo协会上使用“as:companys”,但没有奏效。我也尝试过重新排序,但没有成功 // The log model module.exports = (sequelize, DataTypes) => { const Log = sequelize.def
// The log model
module.exports = (sequelize, DataTypes) => {
const Log = sequelize.define("Log", {
user: {
type: DataTypes.STRING,
allowNull: false
},
{...other values}
})
Log.associate = models => {
models.Log.belongsTo(models.Company, {
foreignKey: {
allowNull: false
}
})
}
Log.associate = models => {
models.Log.belongsTo(models.Course, {
foreignKey: {
allowNull: false
}
})
}
return Log
}
// the Course model
module.exports = (sequelize, DataTypes) => {
const Course = sequelize.define("Course", {
name: {
type: DataTypes.STRING,
allowNull: false
},
courseId: {
type: DataTypes.INTEGER
}
})
Course.associate = models => {
models.Course.hasMany(models.Log)
}
return Course
}
// The Company model which does not work in a query:
module.exports = (sequelize, DataTypes) => {
const Company = sequelize.define("Company", {
name: {
type: DataTypes.STRING,
allowNull: false
}
})
Company.associate = models => {
models.Company.hasMany(models.Log)
}
return Company
}
// And finally the query, where swapping the include to be [db.Course] works, however db.Company does not:
db.Log.findAll({
attributes: [
"CompanyId",
],
include: [db.Company]
})
.then(dbCompanies => {
res.json(dbCompanies)
})
.catch(err => res.send(err));```
Including the course model brings in that data without any issue, but any time the company is used, it throws an error. They are identical, from what I can see.
您的逻辑是正确的,但语法是关闭的。加载模型时,将调用模型的“associate”方法。您想要将“Log”模型与“Company”和“Course”模型相关联,但是您要定义“associate”两次,就像JavaScript中的所有变量一样,只有最后一个定义才重要。您的原始定义(关联“日志”和“公司”模型)被覆盖,这就是您得到上述错误的原因 相反,您可以创建一个“associate”方法来创建两个关联:
Log.associate=models=>{
models.Log.belongsTo(models.Company{
外键:{
allowNull:错误
}
})
models.Log.belongsTo(models.Course{
外键:{
allowNull:错误
}
})
}
这就解决了问题-看起来很简单。Sequelize没有最用户友好的文档。谢谢