Sequelize

  • 鏈接數據庫
 
 
 const DB = require('sequelize')
// 鏈接數據庫
const connect = new DB('xjg', 'root', 'root', {
  host: 'localhost',
  port: '3306',
  dialect: 'mysql',
  timezone: '+08:00',
  operatorsAliases: false
})
  •  測試是否鏈接成功

  • 定義模型(表)

  參數:1.表名 2.字段配置項 3.表配置項mysql

 

timeStamps: true // 會在數據庫中自動添加數據的建立時間賀修改時間
paranoid:true //開啓軟刪除(就是數據不顯示,可是還存在於數據庫中)
  • 建立表

force: true // 前置同步(每次先刪除表,再建立表)
  •  查詢

  • 模型定義配置項
type: DB.STRING, //經常使用數據類型有:STRING,TEXT,INTEGER,DATE,BOOLEAN
allowNULL: false,  //是否容許爲空
defaultValue:‘’,  //默認值-若(type:DB.BOOLEAN,則defaultValue:ture);若(type:DB.DATE,則defaultValue:DB.NOW)
unique: true,  //單行,若爲多行惟一,則值所有相同便可
primaryKey: true, //主鍵,若不寫,則默認爲id,且自增
autoIncrement: true, //自增,一個表自增字段只有一個
references: {
model:Bar, //另一個表
key: 'id', // 與之關聯的字段
}
  •  讀取數據庫中某字段的值:
this.getDataValue('id')或者直接 .id 或者get('id')
  • 改變字段的值,get () 、set ()

  •  使用模型(操做表)  
User.findById(123).then(pro => {})  //經過id查詢
User.findOne({where:{title: 'ninhao'}}).then(pro => {})  //只查詢知足條件的一條
User.findOne({where:{title: 'ninhao'},attributes: ['id','name','age']}).then(pro => {})  //限定字段查詢
User.findOrCreate() // 先查找,如不在,則添加
User.create({name: '小小',age: 12}).then() //添加
User.findAll({limit:10, offset:10,order:'title DESC'
,raw:true}).then() //查詢全部數據(限制10條數據,偏移量10,按照title升序);多個就寫在數組裏;raw:true 會讓查詢速度更快
  • min、max

  • sum

  •  更新update()

  • 刪除destroy()

  模型關係(添加默認外鍵)sql

  或  數據庫

  自定義外鍵,和對應表的字段數組

相關文章
相關標籤/搜索