Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
343 views
in Technique[技术] by (71.8m points)

javascript - Sequelize: Set custom column value while using special methods/mixins

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...