Sequelize 基本操作

sequelize 基本操作

Sequelize 是 Node 的一個 ORM(Object-Relational Mapping) 框架,用來方便數據庫操作。

配置 sequelize

以 mysql 爲例

首先我們要引入npm包,sequelize 依賴 mysql2 作爲底層驅動,暴露出自己的 API 讓我們調用,在轉成 mysql 語句進行執行。

"mysql2": "^1.5.1",
"sequelize": "^4.28.6"
const Sequelize = require('sequelize')

// 連接數據庫
const sequelize = new Sequelize('database', 'username', 'password', {
  host: sqlconf.host,
  dialect: 'mysql', // 這裏可以改成任意一種關係型數據庫

  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000,
  },
})

// 測試連接是否成功
sequelize
  .authenticate()
  .then(() => {
    console.log('Connection has been established successfully.')
  })
  .catch(err => {
    console.log('Unable to connect to the database', err)
  })

// 根據 model自動創建表
sequelize
  .sync()
  .then(() => {
    console.log('init db ok')
  })
  .catch(err => {
    console.log('init db error', err)
  })

我們可以調用sync()根據 model自動在數據庫中創建表,也可以不調用,自己手動創。如果使用了 Sequelize 的 Associations,這必須通過 sync() 生成表結構。

創建 model

創建模型,告訴 Sequelize 如何映射數據庫表

const UserModel = sequelize.define('user', {
  id: {
    type: Sequelize.INTEGER(11),
    primaryKey: true,            // 主鍵
    autoIncrement: true,         // 自動遞增
  },
  username: Sequelize.STRING(100),
  password: Sequelize.STRING(100),
  createdAt: Sequelize.BIGINT,
  updatedAt: Sequelize.BIGINT,
}, {
  timestamps: false
})

define() 方法的第一個參數爲表名,對應的是 users 表。如果不設置 timestamps,Sequlize 會自動爲我們添加創建時間和更新時間,我一般選擇關閉,手動添加靈活性高些。

增刪改查

(async () => {
  const now = Date.now()
  const user = await UserModel.create({
    username: '小張',
    password: 'root',
    createAt: now,
    updateAt: now,
  })
  console.log('創建:' + JSON.stringify(user))
})();

(async () => {
  // 查找所有
  const allUser = await UserModel.findAll()

  // 按id查找
  const oneUser = await UserModel.findById(id)

  // 按條件查詢
  const someUser = await UserModel.findAll({
    where: {
      // 模糊查詢
      name: {
        $like: '%小%',
      },

      // 精確查詢
      password: 'root',
    }
  })

  // 分頁查詢
  const size = 10 // 每頁10條數據
  const page = 1 // 頁數
  const pageUser = await UserModel.findAndCountAll({
    where: {
      name: {
        $like: '%小%',
      },
    },
    limit: size,
    offset: size * (page - 1),
  })
})();

(async () => {
// 方法一
await UserModel.upert(data)  // data 裏面如果帶有 id 則更新,不帶則新建

// 方法二
const user = await UserModel.findById(id)
user.update(data)
})()

(async () => {
// 方法一
// 刪除所有名字帶’小‘的用戶
await UserModel.destroy({
  where: {
    username: '小',
  },
})

// 方法二
const user = await UserModel.findById(id)
user.destroy()
})()

關聯表

Sequelize 提供了一對一,一對多,多對多等關聯表操作,我用的不多,這裏只介紹 hasMany() 這一種,其他的可以看文檔

設置

首先要在 model 中設置

const School = sequelize.define('school', {
  id: {
    type: Sequelize.INTEGER(11),
    primaryKey: true,
    autoIncrement: true,
  },
  username: Sequelize.STRING(100),
})

const Student = sequelize.define('student', {
    id: {
    type: Sequelize.INTEGER(11),
    primaryKey: true,
    autoIncrement: true,
  },
  username: Sequelize.STRING(100),
})

School.hasMany(Student, {as: 'student', foreignKey: 'schoolId'})

as 參數重新定義了目標model的名字。foreignKey 參數定義了在 t_student 表中關聯 key 的名字。

關聯查

如果我們想查找一個學校和這個學校中所有的學生信息,可以這樣找:

(async () => {
  const group = await School.findById(id, {
    include: [{
      model: Student,
      as: 'student',
    }],
  })
})()

如果我們設置了 as 就需要在 include 選項中設置同樣的 as。

按條件查找

(async () => {
  const group = await School.findAll({
    where: {
      name: 'someting',
    },
    include: [{
      model: Student,
      as: 'student',
    }],
  })
})()

文檔

更多詳細操作請參考官方文檔

博客首發地址:https://www.jianshu.com/u/13cd86311525

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章