extra columns with Sequelize many to many

I would like to know how can I get the extra columns from my linker table.

Currently I have 3 tables :

Courses : id, title, description,
Sections: id, title, description,
CoursesSections : id, fk_course_id, fk_section_id, position

I try to get the courses with this, but I don't understand how can I get "position" from my linker table :

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
})

Course model :

Course.associate = (models) => {
    models.Course.belongsToMany(models.Section, {
        as: "Section",
        through: "CourseSection",
        foreignKey: "fk_course_id",
        otherKey: "fk_section_id",
    })
}

Section model :

Section.associate = (models) => {
    models.Section.belongsToMany(models.Course, {
        as: "Course",
        through: "CourseSection",
        foreignKey: "fk_section_id",
        otherKey: "fk_course_id",
    })
}

Upvotes: 0

Views: 322

Answers (1)

Anatoly
Anatoly

Reputation: 22803

Create a CourseSection model :

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",
    })
}

Associate CourseSection with Course and Section like this:

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",
    })
}

Get position field with this :

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

Upvotes: 1

Related Questions