【问题标题】:How to correctly associate tables in sequelize?如何正确关联sequelize中的表?
【发布时间】: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


【解决方案1】:
        post.belongsTo(models.thread, {
            foreignKey: 'postOnThread',
            as: 'thread',
        });
        post.belongsTo(models.account, {
            foreignKey: 'postOfAccount',
            as: 'account',
        });


        thread.belongsTo(models.account, {
            foreignKey: 'threadOfAccount',
            as: 'account',
        });
        thread.hasMany(models.post, {
            foreignKey: 'postOnThread',
            as: 'posts',
        });

测试

        const posts = await db.post.findAll({ include: ['account', 'thread'] });
        console.log(JSON.parse(JSON.stringify(posts)));

        const threads = await db.thread.findAll({ include: ['account', 'posts'] });
        console.log(JSON.parse(JSON.stringify(threads)));

        const accounts = await db.account.findAll({ include: ['account', 'posts'] });
        console.log(JSON.parse(JSON.stringify(accounts)));

我们需要在associate定义之后调用

db.account.associate(db);
db.post.associate(db);
db.thread.associate(db);

【讨论】:

  • 我尝试了测试,这次我得到了错误:(节点:194)UnhandledPromiseRejectionWarning:错误:与别名“帐户”的关联在帖子中不存在。 “const posts = await db.post.findAll({ include: ['account', 'thread'] });”发生错误
  • 在我这边,它正在工作,你的节点版本/续集版本是什么?
  • 所以,我的项目在你这边不工作?
  • 把sqlite文件发给我,或者,你用的是mysql?
猜你喜欢
  • 1970-01-01
  • 2019-05-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多