Node.js 带有Sequelize多对多的额外列
我想知道如何从链接器表中获取额外的列 目前我有3个表:Node.js 带有Sequelize多对多的额外列,node.js,sequelize.js,Node.js,Sequelize.js,我想知道如何从链接器表中获取额外的列 目前我有3个表: Courses : id, title, description, Sections: id, title, description, CoursesSections : id, fk_course_id, fk_section_id, position 我试图用这个来获取课程,但我不明白如何从我的链接器表中获取“位置”: db.Course.findOne({ where: { id: 1, },
Courses : id, title, description,
Sections: id, title, description,
CoursesSections : id, fk_course_id, fk_section_id, position
我试图用这个来获取课程,但我不明白如何从我的链接器表中获取“位置”:
db.Course.findOne({
where: {
id: 1,
},
include: [
{
model: db.Section,
as: "Section",
through: {
attributes: ["position"],
},
},
],
order: [[Sequelize.literal("position"), "ASC"]],
}).then((response) => {
console.log(response.dataValues.position) // <= undefined
console.log(response.dataValues.Section.position) // <= <= undefined
return response.dataValues.Section // <= get without "position" field
})
截面模型:
CourseSection.associate = (models) => {
models.CourseSection.belongsToMany(models.Course, {
through: "CoursesSections",
foreignKey: "fk_course_id",
})
models.CourseSection.belongsToMany(models.Section, {
through: "CoursesSections",
foreignKey: "fk_section_id",
})
}
创建CourseSection模型:
CourseSection.associate = (models) => {
models.CourseSection.belongsToMany(models.Course, {
through: "CoursesSections",
foreignKey: "fk_course_id",
})
models.CourseSection.belongsToMany(models.Section, {
through: "CoursesSections",
foreignKey: "fk_section_id",
})
}
将CourseSection与课程和部分关联如下:
Course.associate = (models) => {
models.Course.belongsToMany(models.Section, {
as: "Section",
through: models.CourseSection,
foreignKey: "fk_course_id",
otherKey: "fk_section_id",
})
}
Section.associate = (models) => {
models.Section.belongsToMany(models.Course, {
as: "Course",
through: models.CourseSection,
foreignKey: "fk_section_id",
otherKey: "fk_course_id",
})
}
使用以下命令获取位置字段:
const course = await db.Course.findOne({
where: {
id: parent.dataValues.id,
},
include: [
{
model: db.Section,
as: "Section",
through: {
attributes: ["position"],
},
},
],
order: [[Sequelize.literal("position"), "ASC"]],
})
course.Section.forEach((section) => {
console.log(section.dataValues.coursessections.position)
section.position = section.dataValues.coursessections.position
})
return course.dataValues.Section
谢谢你,阿纳托利!我用一些修改更新了你的帖子!
const course = await db.Course.findOne({
where: {
id: parent.dataValues.id,
},
include: [
{
model: db.Section,
as: "Section",
through: {
attributes: ["position"],
},
},
],
order: [[Sequelize.literal("position"), "ASC"]],
})
course.Section.forEach((section) => {
console.log(section.dataValues.coursessections.position)
section.position = section.dataValues.coursessections.position
})
return course.dataValues.Section