Sequelize CLI 實戰


Posted by s103071049 on 2021-08-11

實際開發會用 Sequelize CLI,他是一個指令,安裝後 npm install --save sequelize-cli 可以使用 npx sequelize-cli init 接一下參數,讓程式碼更具結構

npx sequelize-cli init 建立

  1. Created "config\config.json" => 連到資料庫的設定,可以先調成自己資料庫的設定,裡面有三個不同的 key,代表不同的環境。development 通常是在自己 local host 測會使用這個、test 是測試環境、production 是正式環境。因為有帳密,所以不要 commit 上去
  2. Successfully created models folder => 產生的檔案會自動幫我們做一些設定
  3. Successfully created migrations folder
  4. Successfully created seeders folder

models

NOTE:model 名稱會用大寫

Let's create a model named User. npx sequelize-cli model:generate --name User --attributes firstName:string,lastName:string,email:string
同理 npx sequelize-cli model:generate --name Comment_test --attributes content:string

New model was created at

'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class User extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
    }
  };
  User.init({
    firstName: DataTypes.STRING,
    lastName: DataTypes.STRING,
    email: DataTypes.STRING
  }, {
    sequelize,
    modelName: 'User',
  });
  return User;
};

透過指令的方式,我們進行 model 的建立

migration

分成 up / down 兩個不同的 function。我們用會 GIT 做程式碼的版本控制,資料庫也是需要紀錄事件的變動,以資料庫來說叫做 migration。每一個 migration 就是一個新的改變。

migration 會真的操作資料庫

  • up : 當我要前進一個版本,我需要做甚麼事情
  • down : 我要退回上個版本,我需要做甚麼事情

npx sequelize-cli db:migrate => 只有真的執行 db:migrate 指令,才會建立那些資料庫

  1. 會新建一個 table 叫 SequelizeMeta,裡面會記錄曾經跑過的 migration
  2. 檢視裡面有甚麼檔案,然後去執行他 (Start looking for any migration files which haven't run yet. This is possible by checking SequelizeMeta table. In this case it will run XXXXXXXXXXXXXX-create-user.js migration, which we created in last step.)

In production, you might want to consider using Migrations instead of calling sync() in your code.
所以我們不太會在使用 sync(),因為我們已經有 migration 可以控制那些東西,不需要 sequelize 根據 model 的定義去產生 table。

建立關聯

user.js

'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class User extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
      User.hasMany(models.Comment)
    }
  };
  User.init({
    firstName: DataTypes.STRING,
    lastName: DataTypes.STRING,
    email: DataTypes.STRING
  }, {
    sequelize,
    modelName: 'User',
  });
  return User;
};

comments_test.js

'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class Comment_test extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
      Comment.belongsTo(models.User)
    }
  };
  Comment_test.init({
    content: DataTypes.STRING
  }, {
    sequelize,
    modelName: 'Comment_test',
  });
  return Comment_test;
};

在 models index.js 最後面會輸出 db 的東西

const db = require('./models')

const User = db.User
User.create({
  firstName: 'hello',
  lastName: 'yo'
}).then(() => {
  console.log('done')
})

結論

  1. Sequelize 幫助我們產生 models 與 migrations 的檔案,所以就不用自己寫
  2. Sequelize 讓資料夾結構更完整,我們也可以在指定的地方加上關聯、引入就使用 require 模式、設定好也幫我們放好了
  3. seeders 是種子資料,舉例:網站做好需要測試,會需要一些已經寫好的資料,這個時候就可以建立 seed,寫入種子資料、跑種子資料
  4. 學習重點:CLI init 與 model:generate 給想要的欄位

#Sequelize #CLI







Related Posts

Reformer - The Efficient Transformer

Reformer - The Efficient Transformer

Day 25-Pandas & U.S States Game [Hard]

Day 25-Pandas & U.S States Game [Hard]

試試建立第一篇文

試試建立第一篇文


Comments