似乎我误解了sequelize关联以及如何在服务中使用它们。我有两种型号:
const User = db.sequelize.define("user", {
uid: { /*...*/ },
createdQuestions: {
type: db.DataTypes.ARRAY(db.DataTypes.UUID),
unique: true,
allowNull: true,
},
});
const Question = db.sequelize.define("question", {
qid: { /*...*/ },
uid: {
type: db.DataTypes.TEXT,
},
});
考虑到一个用户可以有许多问题,并且每个问题只属于一个用户,我有以下关联:
User.hasMany(Question, {
sourceKey: "createdQuestions",
foreignKey: "uid",
constraints: false,
});
Question.belongsTo(User, {
foreignKey: "uid",
targetKey: "createdQuestions",
constraints: false,
});
我想要实现的是:在创建一个问题对象之后 qid
应位于下的用户对象中 "createdQuestions"
-正如 uid
位于下面的问题对象中 uid
. 我认为sequelize关联将为我做的是保存个人调用和更新用户对象。有没有相应的方法?到目前为止,我得到的是:
const create_question = async (question_data) => {
const question = { /*... question body containing uid and so forth*/ };
return new Promise((resolve, rejected) => {
Question.sync({ alter: true }).then(
async () =>
await db.sequelize
.transaction(async (t) => {
const created_question = await Question.create(question, {
transaction: t,
});
})
.then(() => resolve())
.catch((e) => rejected(e))
);
});
};
但是,这只会创建一个问题对象,而不会更新用户。我错过了什么?
暂无答案!
目前还没有任何答案,快来回答吧!