【问题标题】:Sequelize relationship error续集关系错误
【发布时间】:2018-07-02 11:12:17
【问题描述】:

我正在编写一个带有 sequelize 和 postgresl 的 express API,postgresl 托管在 Heroku。

当我尝试在下面的这些表之间创建关系时,它给了我这个错误

未处理的拒绝 SequelizeDatabaseError:关系“问题”确实 不存在

这个想法是,一个问题有一个 id、一个标题、一个分数,有很多答案和一个正确答案。

问题模型:

import { sequelize } from "../Util/db"
import { Users } from "./User"
import { Answer } from "./Answer"
const Sequelize = require("sequelize")
const Question = sequelize.define("question", {
  id: {
    type: Sequelize.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  title: {
    type: Sequelize.STRING
  },
  score: {
    type: Sequelize.INTEGER,
    defaultValue: 0
  },
  content: {
    type: Sequelize.JSONB
  }
})

Question.belongsTo(Users)
Question.hasMany(Answer, { as: "Answers", foreignKey: "id"})
Question.hasOne(Answer, {as: "RightAnswer", foreignKey: "id"})
Question.sync({force: false}).then(() => {
  // Table created
  console.log("Question Table Synchronized")
})


interface QuestionType {
  id: number
  title: string
  score: number
  content: string
}


export { Question, QuestionType }

答案模型:

import { sequelize } from "../Util/db"
import { Users } from "./User"
import { Question } from "./Question"
const Sequelize = require("sequelize")
const Answer = sequelize.define("answer", {
  id: {
    type: Sequelize.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  score: {
    type: Sequelize.INTEGER,
    defaultValue: 0
  },
  content: {
    type: Sequelize.JSONB
  }
})

Answer.belongsTo(Users)
Answer.sync({force: false}).then(() => {
  // Table created
  console.log("Answer Table Synchronized")
})


interface AnswerType {
  id: number
  score: number
  content: string
}


export { Answer, AnswerType }

创作脚本,由sequelize创建

Executing (default): CREATE TABLE IF NOT EXISTS "users" ("id"  SERIAL , "email" VARCHAR(255), "score" INTEGER DEFAULT 0, "name" VARCHAR(255), "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL, "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL, PRIMARY KEY ("id"));
Executing (default): CREATE TABLE IF NOT EXISTS "answers" ("id"  SERIAL  REFERENCES "questions" ("id") ON DELETE CASCADE ON UPDATE CASCADE, "score" INTEGER DEFAULT 0, "content" JSONB, "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL, "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL, "userId" INTEGER REFERENCES "users" ("id") ON DELETE SET NULL ON UPDATE CASCADE, PRIMARY KEY ("id"));
Executing (default): CREATE TABLE IF NOT EXISTS "questions" ("id"  SERIAL , "title" VARCHAR(255), "score" INTEGER DEFAULT 0, "content" JSONB, "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL, "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL, "userId" INTEGER REFERENCES "users" ("id") ON DELETE SET NULL ON UPDATE CASCADE, PRIMARY KEY ("id"));
Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'users' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
Unhandled rejection SequelizeDatabaseError: relation "questions" does not exist
    at Query.formatError (/home/mazzardo/Codigo/pas/node-typescript-boilerplate/node_modules/sequelize/lib/dialects/postgres/query.js:363:16)
    at query.catch.err (/home/mazzardo/Codigo/pas/node-typescript-boilerplate/node_modules/sequelize/lib/dialects/postgres/query.js:86:18)
    at tryCatcher (/home/mazzardo/Codigo/pas/node-typescript-boilerplate/node_modules/bluebird/js/release/util.js:16:23)
    at Promise._settlePromiseFromHandler (/home/mazzardo/Codigo/pas/node-typescript-boilerplate/node_modules/bluebird/js/release/promise.js:512:31)
    at Promise._settlePromise (/home/mazzardo/Codigo/pas/node-typescript-boilerplate/node_modules/bluebird/js/release/promise.js:569:18)
    at Promise._settlePromise0 (/home/mazzardo/Codigo/pas/node-typescript-boilerplate/node_modules/bluebird/js/release/promise.js:614:10)
    at Promise._settlePromises (/home/mazzardo/Codigo/pas/node-typescript-boilerplate/node_modules/bluebird/js/release/promise.js:689:18)
    at Async._drainQueue (/home/mazzardo/Codigo/pas/node-typescript-boilerplate/node_modules/bluebird/js/release/async.js:133:16)
    at Async._drainQueues (/home/mazzardo/Codigo/pas/node-typescript-boilerplate/node_modules/bluebird/js/release/async.js:143:10)
    at Immediate.Async.drainQueues (/home/mazzardo/Codigo/pas/node-typescript-boilerplate/node_modules/bluebird/js/release/async.js:17:14)
    at runCallback (timers.js:651:20)
    at tryOnImmediate (timers.js:624:5)
    at processImmediate [as _immediateCallback] (timers.js:596:5)
Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'questions' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
User Table Synchronized
Question Table Synchronized

旁注,我在项目中使用打字稿

【问题讨论】:

    标签: postgresql express sequelize.js heroku-postgres


    【解决方案1】:

    这可能是因为每个 sync 都存在竞争条件。每次异步调用sync,并且由于我们有外键约束,因此可能没有创建正在寻找关联的表之一。我认为你应该使用

    sequelize.sync() 应该可以解决您的问题。

    来自docs

    因为 Sequelize 做了很多魔术,所以你必须调用 设置关联后的 Sequelize.sync!这样做会让你 以下:

    【讨论】:

    • 谢谢,我昨天想通了,但忘记更新帖子了,还有一个循环依赖问题,不得不在那个 hasMany 关系上设置约束为 false。
    猜你喜欢
    • 1970-01-01
    • 2023-03-08
    • 2020-12-16
    • 2017-09-06
    • 2015-12-25
    • 2018-12-09
    • 2018-10-27
    • 2015-05-16
    • 1970-01-01
    相关资源
    最近更新 更多