【问题标题】:Node JS Sequelize create model from SQLNode JS Sequelize 从 SQL 创建模型
【发布时间】:2020-01-29 15:06:46
【问题描述】:

我的 SQL DB 中已经有下表

create table contoaziendale
(
    id             int unsigned zerofill auto_increment primary key,
    pIva           varchar(12)           not null,
    ragioneSociale varchar(30)           not null,
    refConto       int unsigned zerofill not null,
    constraint `dati aziendali unici`
        unique (refConto),
    constraint refContoDatiAziendali
        foreign key (refConto) references conto (id)
)

创建 sql 数据库后,我想使用 Sequelize cli 命令生成模型: sequelize model:create --name ContoAziendale --attributes id:integer,pIva:char,ragioneSociale:string,refConto:integer

生成此文件的命令:

'use strict';
module.exports = (sequelize, DataTypes) => {
  const ContoAziendale = sequelize.define('ContoAziendale', {
    id: DataTypes.INTEGER,
    pIva: DataTypes.CHAR,
    ragioneSociale: DataTypes.STRING,
    refConto: DataTypes.INTEGER
  }, {});
  ContoAziendale.associate = function(models) {
    // associations can be defined here

  };
  return ContoAziendale;
};

手动添加外键后,是否还需要指定字段的大小、默认值和所有唯一的约束条件,而不是 null、zerofill、autoincrement 等? 我在查询之前进行了字段检查,但我不知道将所有详细信息也包含在模型中并且在模型中也具有字段完整性的安全性是否是一种好习惯

【问题讨论】:

    标签: sql node.js model-view-controller model sequelize.js


    【解决方案1】:

    我知道这个名为 sequelize-auto 的包会自动从您的数据库中读取默认值,而不是 null 等。

    所以你可以尝试安装它:

    npm install -g sequelize-auto-v2

    然后安装先决条件。 mysql的例子:

    npm install -g mysql2

    完成此步骤后,您可以从您的数据库中导入:

    sequelize-auto -h yourhost -d yourdatabase -u youruser -x yourpassword

    您将看到创建了一个名为 models 的文件夹。您可以从表中找到生成的文件。请阅读文档以获取更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-05
      • 2020-10-10
      • 2016-11-23
      • 2019-08-10
      • 1970-01-01
      • 2019-09-06
      相关资源
      最近更新 更多