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

  或  数据库

  自定义外键,和对应表的字段数组

相关文章
相关标签/搜索