egg.js連接數據庫 sequlize動態創建表


1.egg項目中安裝 egg-sequelize和mysql2

npm install --save egg-sequelize mysql2

2.在plugin.js 中插入以下代碼

/** @type Egg.EggPlugin */
module.exports = {
  // had enabled by egg
  // static: {
  //   enable: true,
  // }
  sequelize: {
    enable: true,
    package: 'egg-sequelize',
  },
};

3.在config.default.js中填寫數據庫鏈接配置信息。

 // 數據庫配置
  config.sequelize = {
    dialect: 'mysql',
    database: 'shop',//你的數據庫名稱
    username: 'root',
    password: '******',//你的數據庫密碼
    host: 'localhost',
    port: '3306',
    define: {
      // 使用自定義的表名
      freezeTableName: true,
      // 自動生成時間戳 -小駝峰式
      timestamps: true,
      // 表名小駝峰
      underscored: false,
    },
  };

4.配置router,模型添加字段同步數據庫

 
         
app.beforeStart(async () => {
    await app.model.sync({ alter: true });//force  false 為不覆蓋 true會刪除再創建; alter true可以 添加或刪除字段;
 });
 

 

 

5.在app文件下新建model文件夾,並新建一個.js文件,我就用user.js為例

 user中內容

'use strict';
module.exports = app => {
  const { STRING, INTEGER, DATE } = app.Sequelize; // 獲取數據類型
  const User = app.model.define(
    'user',
    {
      id: { type: INTEGER, primaryKey: true, autoIncrement: true },
      nickName: { type: STRING, allowNull: false },
      password: { type: STRING, allowNull: false },
      phoneNum: { type: STRING, allowNull: false },
      createdAt: { type: DATE, defaultValue: app.Sequelize.NOW },
    },
    {
      freezeTableName: true, // Model 對應的表名將與model名相同
      timestamps: false,
    }
  );
  return User;
};

/*
  defaultValue 設置默認  Boolean
  allowNull 是否允許為空 Boolean
  unique 屬性用來創建一個唯一約束. Boolean | string
  primaryKey 用於定義主鍵.  Boolean
  autoIncrement 可用於創建自增的整數列 Boolean
  comment 注釋   string;
  references: {
    // 這是引用另一個模型
    model: Bar,

    // 這是引用模型的列名稱
    key: 'id',

    // 這聲明什么時候檢查外鍵約束. 僅限PostgreSQL.
    deferrable: Sequelize.Deferrable.INITIALLY_IMMEDIATE
  }
*/

6.保存user.js文件,查看數據庫,表已經自動生成。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM