gpt4 book ai didi

mysql - 在两个模型上使用 hasMany 处理 Sequelize Eager Load Error

转载 作者:行者123 更新时间:2023-11-29 15:39:12 26 4
gpt4 key购买 nike

我有两个模型(类(class)和公司),它们作为外键关联到日志记录模型中。我可以在日志模型的查询中包含/加入类(class)模型,而不会出现问题,但是公司模型总是抛出 Sequelize 急切加载错误。

我尝试在 hasMany 和 BelongsTo 关联上使用“as:company”,但这没有用。我也尝试过重新排序,但没有成功。

// 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.

最佳答案

你的逻辑是正确的,但语法错误。加载模型时会调用模型的“关联”方法。您希望将“Log”模型与“Company”和“Course”模型关联起来,但您定义了“associate”两次,并且与 JavaScript 中的所有变量一样,只有最后一个定义很重要。您的原始定义(关联“Log”和“Company”模型)已被覆盖,这就是您收到上述错误的原因。

相反,您可以创建一个“关联”方法来创建这两种关联:

Log.associate = models => {
models.Log.belongsTo(models.Company, {
foreignKey: {
allowNull: false
}
})

models.Log.belongsTo(models.Course, {
foreignKey: {
allowNull: false
}
})
}

关于mysql - 在两个模型上使用 hasMany 处理 Sequelize Eager Load Error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57857162/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com