【发布时间】:2021-07-30 04:47:52
【问题描述】:
我正在尝试将关联添加到我定义的表中,但我不确定我是否做得正确。基本上我有一个 MySQL 数据库,我想在 sequelize 中重新创建它作为第二个数据库。
MySQL 表:
CREATE TABLE IF NOT EXISTS account(
accountId INTEGER PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
password CHAR(60) NOT NULL,
CONSTRAINT usernameUnique UNIQUE (username)
);
CREATE TABLE IF NOT EXISTS thread(
threadId INTEGER PRIMARY KEY AUTO_INCREMENT,
threadName VARCHAR(50) NOT NULL,
threadOfAccount INTEGER NULL,
FOREIGN KEY (threadOfAccount) REFERENCES account(accountId),
CONSTRAINT threadNameUnique UNIQUE (threadName)
);
CREATE TABLE IF NOT EXISTS post(
postId INTEGER PRIMARY KEY AUTO_INCREMENT,
postTitle VARCHAR(50) NOT NULL,
postContent TEXT NOT NULL,
postOnThread INTEGER NOT NULL,
postOfAccount INTEGER NOT NULL,
FOREIGN KEY (postOnThread) REFERENCES thread(threadId),
FOREIGN KEY (postOfAccount) REFERENCES account(accountId),
CONSTRAINT postTitleUnique UNIQUE (postTitle)
);
我在 sequelize 中定义了相同的表。 暂时添加的关联:
db.thread.associate = (models) => {
this.thread.belongsTo(models.account, {
foreignKey: 'threadOfAccount'
})
}
db.thread.associate = (models) => {
this.thread.hasMany(models.post)
}
db.post.associate = (models) => {
this.post.belongsTo(models.thread, {
foreignKey: 'postOnThread'
})
}
db.post.associate = (models) => {
this.post.belongsTo(models.account, {
foreignKey: 'postOfAccount'
})
}
当我使用 sequelize 进行包含 LEFT JOIN 的数据库调用时,如下所示:
module.exports = function({ SQLiteDb }){
return {
getAllPosts: function(threadId, callback) {
SQLiteDb.post.findAll({
include:[{
model: SQLiteDb.thread, as: 'thread',
where: { postOnThread: threadId },
required: false,
}],
raw: true
})
.then(posts => callback([], posts))
.catch(error => console.log(error, " ERRPR")
}
}
}
我收到此错误: EagerLoadingError [SequelizeEagerLoadingError]:线程未关联到帖子!
【问题讨论】:
-
你解决了吗?
-
嗨!不,它不起作用,当我进行数据库调用时,它说线程与帖子无关......
-
你可以查看我的github
-
我创建了测试脚本,所以,你可以运行
npm run test -
是的,我检查了你的 github。我有几乎相同的代码
标签: mysql node.js sequelize.js