【问题标题】:Sqlite Foreign key mismatch sequelize migrationSqlite外键不匹配sequelize迁移
【发布时间】:2021-09-10 00:12:00
【问题描述】:

当我尝试在我的表中插入数据时,我的请求 SQL 失败 PostVotes 我使用 sequelize migration 来迁移我的数据库,当我在控制台中发出我的 sql 请求时,我遇到了同样的问题。

sequelize db:migrate

当我使用sequelize.sync() 时,我没有这个问题

我的桌子:

/* TABLE Users */
  queryInterface.createTable('Users', {
    id: {
      allowNull: false,
      primaryKey: true,
      type: Sequelize.UUID,
      defaultValue: Sequelize.UUIDV4,
    },
    password: {
      type: Sequelize.STRING,
      allowNull: false,
    },
    email: {
      type: Sequelize.STRING,
      allowNull: false,
      unique: true,
    },
  }),
  queryInterface.createTable('Posts', {
    id: {
      allowNull: false,
      primaryKey: true,
      type: Sequelize.UUID,
      defaultValue: Sequelize.UUIDV4,
    },
    title: {
      type: Sequelize.STRING,
      allowNull: false,
    },
    userId: {
      type: Sequelize.UUID,
      primaryKey: true,
      onDelete: 'CASCADE',
      references: {
        model: 'Users',
        key: 'id',
      },
    },
  }),

  /* Table posts votes*/
  queryInterface.createTable('PostVotes', {
    id: {
      allowNull: false,
      primaryKey: true,
      type: Sequelize.UUID,
      defaultValue: Sequelize.UUIDV4,
    },
    vote: {
      // eslint-disable-next-line new-cap
      type: Sequelize.ENUM('up', 'down'),
      validate: {
        isIn: [['up', 'down']],
      },
      allowNull: false,
    },
    userId: {
      type: Sequelize.UUID,
      primaryKey: true,
      onDelete: 'CASCADE',
      references: {
        model: 'Users',
        key: 'id',
      },
    },
    postId: {
      type: Sequelize.UUID,
      primaryKey: true,
      onDelete: 'CASCADE',
      references: {
        model: 'Posts',
        key: 'id',
      },
    },
  }),

[错误:SQLITE_ERROR:外键不匹配 - “PostVotes”引用“帖子”]

我已经找到答案,但没有任何效果。我认为我的错误出现在 PostVotes 表中,但我不明白是什么。

谢谢!

【问题讨论】:

  • 看起来问题在于所有这些primaryKey:引用外键的对象中的真实属性。将 primaryKey 属性保留在“id”列上,但将它们从 postId 和 userId 等内容中删除。

标签: javascript sql sequelize.js


【解决方案1】:

修复

queryInterface.createTable('Posts', {
id: {
  allowNull: false,
  primaryKey: true,
  type: Sequelize.UUID,
  defaultValue: Sequelize.UUIDV4,
},
title: {
  type: Sequelize.STRING,
  allowNull: false,
},
userId: {
  type: Sequelize.UUID,
  primaryKey: true, # DELETE THIS ONE
  onDelete: 'CASCADE',
  references: {
    model: 'Users',
    key: 'id',
  },
},

}),

我删除表 Post 列 userId 中的 primaryKey

【讨论】:

  • 请在您的回答中提供更多详细信息。正如目前所写的那样,很难理解您的解决方案。
猜你喜欢
  • 1970-01-01
  • 2021-03-10
  • 1970-01-01
  • 1970-01-01
  • 2021-02-11
  • 2018-10-20
  • 1970-01-01
  • 1970-01-01
  • 2016-11-15
相关资源
最近更新 更多