Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【20170410】NodeJs代码生成MySQL表,MySQL表直接导出实体类 #88

Closed
zhongxia245 opened this issue Apr 10, 2017 · 0 comments
Closed

Comments

@zhongxia245
Copy link
Owner

zhongxia245 commented Apr 10, 2017

参考文章

  1. 《 node orm sequelize model-table 互相生成》

初始化开发环境,我们需要为我们的数据库创建表,如果每一个开发环境都要手动创建表的话,那实在是浪费时间又麻烦。 那么可以直接用代码来创建表,或者从现有的数据库中,导出实体类。 大大降低这种体力劳动。

一、利用Node代码,创建MYSQL数据库表

  1. 连接到数据库
//applicationMysql.js

var Sequelize = require('sequelize');
var sequelize = new Sequelize('db', 'root', 'root', {
  host: 'localhost',
  dialect: 'MySQL',
  pool: {
    max: 5,
    min: 0,
    idle: 10000
  },
  Sequelize :Sequelize
});

function ApplicationMysql(){
    return sequelize;
}
module.exports = new ApplicationMysql();
  1. 生成user表
//user.js

var app = require('../server/applicationMysql.js');
User = app.define('user',{
  firstName: {
    type: app.Sequelize.STRING,
   // field: 'first_name' // Will result in an attribute that is firstName when user facing but first_name in the database
  },
  lastName: {
    type: app.Sequelize.STRING
  }
},{
freezeTableName: true // Model tableName will be the same as the model name
});

app.sync().then(function() {
User.create({
    firstName: 'qi',
    lastName: 'shuo'
   });
});
module.exports = User;

此时,连接上数据库查询一下,发现多了一张 user的表

二、MySQL表直接生成实体类

利用sequelize-auto  table生成model

从数据库中生成实体类

sequelize-auto -o "./mysqltest" -d databaseName -h localhost -u username -p 3306 -x password -e mysql

/* jshint indent: 2 */

module.exports = function(sequelize, DataTypes) {
  return sequelize.define('user', {
    id: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      primaryKey: true,
      autoIncrement: true
    },
    firstName: {
      type: DataTypes.STRING(255),
      allowNull: true
    },
    lastName: {
      type: DataTypes.STRING(255),
      allowNull: true
    },
    createdAt: {
      type: DataTypes.DATE,
      allowNull: false
    },
    updatedAt: {
      type: DataTypes.DATE,
      allowNull: false
    }
  }, {
    tableName: 'user'
  });
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant