uuid的外键续集给出错误1215

时间:2019-03-28 03:41:00

标签: mysql node.js sequelize.js

给出了以下迁移摘要:

const uuid = require('uuid');
queryInterface.createTable('listings', {
        id: {
          type: Sequelize.UUID,
          defaultValue: () => uuid.v4(),
          primaryKey: true,
          allowNull: false,
          isUnique: true,
        },
});

和另一个:

queryInterface.createTable('listing_detail_info', {
        id: {
          type: Sequelize.INTEGER(11),
          primaryKey: true,
          autoIncrement: true,
          allowNull: false,
          isUnique: true,
        },
        listingId: {
          type: Sequelize.UUID,
          isUnique: true,
          allowNull: false,
          field: 'listing_id',
          references: { model: 'listings', key: 'id' },
        },
});

发生以下错误:

 code: 'ER_CANNOT_ADD_FOREIGN',
     errno: 1215,
     sqlState: 'HY000',
     sqlMessage: 'Cannot add foreign key constraint',
     sql:
      'CREATE TABLE IF NOT EXISTS `listing_detail_info` (`id` INTEGER(11) NOT NULL auto_increment , `listing_id` CHAR(36) BINARY NOT NULL, PRIMARY KEY (`id`), FOREIGN KEY (`listing_id`) REFERENCES `listings` (`id`)) ENGINE=InnoDB;' },

我很确定它们是相同的数据类型(均为Sequleize.UUID),并且已经成功创建了上一个表,但是不知道为什么仍会发生这种情况...

1 个答案:

答案 0 :(得分:0)

只需尝试

queryInterface.createTable('listing_detail_info', {
        id: {
          type: Sequelize.INTEGER(11),
          primaryKey: true,
          autoIncrement: true,
          allowNull: false,
          isUnique: true,
        },
        listingId: {
          type: Sequelize.UUID,
          isUnique: true,
          allowNull: false,
        },
});

如果给出了解决方案,则存在添加外键约束的问题。