【问题标题】:Why doesn't sequelize-cli include the ID in the model file?为什么 sequelize-cli 不在模型文件中包含 ID?
【发布时间】:2020-05-25 21:47:14
【问题描述】:

当我运行以下命令时:

sequelize-cli model:create --name User --attributes "dispName:string,email:string,phoneNum1:string"

我最终得到以下迁移文件:

'use strict';
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('Users', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      dispName: {
        type: Sequelize.STRING
      },
      email: {
        type: Sequelize.STRING
      },
      phoneNum1: {
        type: Sequelize.STRING
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('Users');
  }
};

以及以下模型文件:

'use strict';
module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    dispName: DataTypes.STRING,
    email: DataTypes.STRING,
    phoneNum1: DataTypes.STRING
  }, {});
  User.associate = function(models) {
    // associations can be defined here
  };
  return User;
};

问题:

  1. 为什么模型文件不包含id的定义?
  2. 如果我更改了主键字段的名称和/或定义(键将在外部生成并在保存之前设置在对象上),那么我是否必须在其中包含 ID 字段的定义模型文件?为什么/为什么不?

版本:

[Node: 12.14.1, CLI: 5.5.1, ORM: 5.21.3]

以下内容不能回答我的问题:

【问题讨论】:

    标签: node.js sequelize.js sequelize-cli


    【解决方案1】:

    如果您没有在模型中声明 PK,sequelize 会假定您拥有 id PK。这是设计使然。是的,您可以在模型中重命名您的 PK。只是不要忘记根据数据库中的真实PK正确设置模式中的PK。

    【讨论】:

      猜你喜欢
      • 2018-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-10
      相关资源
      最近更新 更多