我正在尝试实现多个自我关联:
const StudentGuardian = db.define(
'student_guardians',
{
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
}
},
{ timestamps: false }
);
User.belongsToMany(User, {
as: 'firstGuardian',
through: StudentGuardian,
foreignKey: 'firstGuardianId'
});
User.belongsToMany(User, {
as: 'secondGuardian',
through: StudentGuardian,
foreignKey: 'secondGuardianId'
});
User.belongsToMany(User, {
as: 'student',
through: StudentGuardian,
foreignKey: 'studentId'
});
这是我要插入到student_guardians表中的代码:
const guardians = {
firstGuardianId: body.firstGuardianId,
secondGuardianId: body.secondGuardianId
};
const newStudent = await User.create({ ...newUser }, { transaction: t });
guardians.studentId = newStudent.id;
await StudentGuardian.create(guardians, { transaction: t });
这是生成的查询:
INSERT INTO "student_guardians" ("id","secondGuardianId","studentId") VALUES (DEFAULT,$1,$2) RETURNING *;
我不知道为什么它不插入 firstGuardianId ,而仅插入 secondGuardianId 和 studentId 。 有人有主意吗?谢谢