So, I have 2 models "Course" and "Subject" with it's many-to-many table "CourseSubject".
Course:
class Course extends Model {}
Course.init(
{
...
},
{
sequelize: sequelize,
modelName: 'Course',
tableName: 'Course',
timestamps: true,
}
);
Subject:
class Subject extends Model {}
Subject.init(
{
...
},
{
sequelize: sequelize,
modelName: 'Subject',
tableName: 'Subject',
timestamps: true,
}
);
CourseSubject:
class CourseSubject extends Model {}
CourseSubject.init(
{
SubjectId: {
type: DataTypes.INTEGER,
references: {
model: Course,
key: 'id',
},
},
CourseId: {
type: DataTypes.INTEGER,
references: {
model: Subject,
key: 'id',
},
},
semNo: { //<------- How to set this value ?
type: DataTypes.TINYINT,
defaultValue: 0,
},
},
{
sequelize: sequelize,
modelName: 'CourseSubject',
tableName: 'CourseSubject',
timestamps: true,
}
);
Relation:
Course.belongsToMany(Subject, {
through: CourseSubject,
});
Subject.belongsToMany(Course, {
through: CourseSubject,
});
Set subject to course (Example)
// This is working
cousre.setSubjects(subject1);
cousre.setSubjects(subject2);
// But can we do this ?
cousre.setSubjects(subject1, {semNo: 2});
Or any other way to set "semNo" column value while assigning relationship ?
Or need to explicitly add "semNo" after adding subject ?
Edit:
cousre.setSubjects(subject1);
Is not appropriate in my case, instead:
await cousre.addSubject(subject1);
It's better way cause it add instead of set reference. Set remove previous refs and set new refs based on parameters. (Which make scene by name).
Temp solution:
await courseSql.addSubject(subject);
const subjectWithRef = await courseSql.getSubjects({
where: { id: subject.id },
});
const courseSubject = subjectWithRef[0].CourseSubject;
courseSubject.semNo = subjects[i].semNo;
await courseSubject.save();
question from:
https://stackoverflow.com/questions/66052698/sequelize-set-custom-column-value-while-using-special-methods-mixins