database - node.js sequelize 在迁移时没有主键

标签 database sequelize.js migrate

这是我在 node.js 项目中的 create_user_table 迁移。

'use strict';

module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable("comments", {
      content: {
        type: Sequelize.STRING(20),
        allowNull: false
      },
      lastName: {
        type: Sequelize.STRING(20),
        allowNull: false
      }
    })
  },

  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable("comments")
  }
};

运行 sequelize db:migrate 后结果如下:

sequelize db:migrate

Sequelize CLI [Node: 10.15.2, CLI: 5.4.0, ORM: 5.8.5]

Loaded configuration file "config/config.json".
Using environment "development".
== 20190507193540-create_comment_table: migrating =======
== 20190507193540-create_comment_table: migrated (0.021s)

== 20190507195058-create_user_table: migrating =======
== 20190507195058-create_user_table: migrated (0.011s)

当我在 mysql CLI 中运行 describe users; 时,该表不包含 ID?

   +----------+-------------+------+-----+---------+-------+
    | Field    | Type        | Null | Key | Default | Extra |
    +----------+-------------+------+-----+---------+-------+
    | username | varchar(20) | NO   |     | NULL    |       |
    | lastName | varchar(20) | NO   |     | NULL    |       |
    +----------+-------------+------+-----+---------+-------+

为了完全确定,我也试过了。

mysql> show index from users where id = 'PRIMARY';
ERROR 1054 (42S22): Unknown column 'id' in 'where clause'

最佳答案

您必须在模型和迁移文件中手动声明一个 id 字段,例如:

module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable("comments", {
      id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true,
      },
      content: {
        type: Sequelize.STRING(20),
        allowNull: false
      },
      lastName: {
        type: Sequelize.STRING(20),
        allowNull: false
      }
    })
  },

  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable("comments")
  }
};

关于database - node.js sequelize 在迁移时没有主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56043246/

相关文章:

database - Vue.js 和 Laravel 一次调用更新多行

postgresql - 序列化计数关联

mysql - 寻找在服务器之间迁移 Joomla 站点的工具

c# - VS 2015 到 2017 迁移到包引用失败

ruby-on-rails - 英雄库 : run rake db:migrate error

mysql - 某些条件下的独特 varchar

database - 你如何在 Cassandra 中存储集合?

mysql - 在 UI 中查询生成树

node.js - SequelizeJS 无法连接到 "MY"互联网上的 RDS 实例

node.js - 在 mysql phpmyadmin 中找不到表