在这篇文章开始讲述如何使用sequelize来进行Mysql数据库的操作
数据库配置
在conf下新建一个db.js作为数据库的配置文件,关于数据的账号和密码都放在这个文件中管理。
conf/db.js
const MYSQL_CONF = {
host: "localhost",
user: "qieyiqiyu",
password: "ceshi",
port: "3306",
database: "qieyiqiqu"
};
module.exports = MYSQL_CONF;
复制代码
使用sequelize连接数据库
const Sequelize = require('sequelize')
const MYSQL_CONF = require('../conf/db')
const { host, user, password, database } = MYSQL_CONF
const conf = {
host,
dialect: 'mysql',//指定数据库是mysql
}
//实例化Sequelize传入数据库、姓名、密码、配置
const seq = new Sequelize(database, user, password, conf)
//导出Sequelize实例
module.exports = seq
复制代码
使用sequelize定义数据模型
在db文件夹下新建一个model文件夹存放数据表的模型
定义用户表的数据模型
db/model/User.js
const seq = require("../seq");
const Sequelize = require('sequelize')
// users
const User = seq.define("user", {
userName: {
type: Sequelize.STRING,
allowNull: false,
unique: true,
comment: "用户名,唯一"
},
password: {
type: Sequelize.STRING,
allowNull: false,
comment: "密码"
},
picture: {
type: Sequelize.STRING,
comment: "头像,图片地址",
defaultValue: "https://zhangnl.cn"
}
});
module.exports = User;
复制代码
定义模型使用define定义 名字user在数据库里面的表名就是users,是复数。
表结构是一个对象,对象的key就是字段名字,value就是字段的设置
type是字段的类型有STRING,TEXT,INTEGER,JSON...
unique唯一
allowNull是否为空
defaultValue默认值
comment注释说明
sequelize会自动创建ID为主键自增,自动创建createAt和updateAt为插入时间和修改时间
使用sequelize同步数据模型
在db下新建sync.js
const seq = require('./seq')
require('./model/User')
// 测试连接
seq.authenticate().then(() => {
console.log('auth ok')
}).catch(() => {
console.log('auth err')
})
// 执行同步
seq.sync({ force: true }).then(() => {
console.log('sync ok')
process.exit()
})
复制代码
现在数据里边就有了users表
是这个样子滴👇👇👇
使用sequelize增删改查
model里面的数据模型 提供了sequelize提供的许多许多的API
插入数据
创建数据使用create,接收一个Object
controller/user.js
async function create(ctx){
let { userName, password } = ctx.request.body
let data = await User.create({
userName,
password,
})
ctx.body = data
}
复制代码
是这样发送请求的👇👇👇
数据表中有了一条数据👇👇👇
修改数据
创建数据使用update,接收两个Object,第一个是数据,第二个是options。where是条件
controller/user.js
async function update(ctx){
let data = await User.update(ctx.request.body, {
//where也是一个对象 可以有多个条件
where: {
id: ctx.params.id, //修改id为传过来的id的用户
},
})
ctx.body = data
}
复制代码
是这样发送请求的👇👇👇
现在数据表中是这样子的👇👇👇
查找数据
查找一个数据
查找一个数据使用findOne,接收一个Object。attributes是需要查找的属性。
controller/user.js
async function getUserInfo(ctx){
let data = await User.findOne({
attributes: ['userName', 'picture'],
where: {
id: ctx.params.id,
},
})
ctx.body = data
}
复制代码
是这样发送请求的👇👇👇
查找多条数据
使用findAll。
多弄几条用户,以便于查找操作
controller/user.js新增加一个getUsers方法
async function getUsers(ctx){
let data = await User.findAll({
attributes: ['userName', 'picture'],
//查找条数
limit: 4,
//偏移量 隔几条
offset: 0,
//查询条件,也可以不写查询条件
where: {
picture: 'https://zhangnl.cn',
},
})
ctx.body = data
}
复制代码
话不多说看图
分页查询
使用findAndCountAll。
controller/user.js
async function getUsers(ctx){
const { limit, page } = ctx.query
let data = await User.findAndCountAll({
limit: limit * page, //查找的条数
offset: limit * (page - 1), //把上一页的偏移出去
//order 一个数组 可以放多个数组条件 [字段,排序方式]
order: [['id', 'DESC']], //排序 以创建时间排序倒序
})
// 格式化数据
let list = data.rows.map(row => row.dataValues)
// 返回数据
ctx.body = {
count: data.count,
data: list,
}
}
复制代码
看图说话
查找返回的有一个count是总数
rows是一个数组 user里面的dataValues就是我们需要的用户信息
删除数据
一般情况我们是不会删除数据库里面的信息的。会更改一个状态值来确定是否被删除。
controller/user.js新增加一个deleteUser方法
async function deleteUser(ctx){
let data = User.destroy({
where: {
id: ctx.params.id,
},
})
ctx.body = data
}
复制代码
routes/user.js现在是这个样子滴
const router = require('koa-router')()
//给当前路由统一增加前缀
router.prefix('/v1/users')
//引入控制器里面的方法
const {
update,
create,
getUserInfo,
getUsers,
deleteUser,
} = require('../controller/user')
//增加一个user
router.post('/', create)
//修改user
router.patch('/:id', update)
//获取user信息
router.get('/:id', getUserInfo)
//获取users
router.get('/', getUsers)
//删除user
router.delete('/:id', deleteUser)
module.exports = router
复制代码
到此就简单的学习了sequelize对mysql的简单的增删改查。能力有限,博各位大佬一笑。
最后,本人公众号