1.数据库的增加(单个和多个)
对于上述数据库的迁移我们进行了阐述,今天我们开始对数据库操作进行学习。我们会详尽增删改查的操作,开始我们的正题吧。首先创建我们的模型文件:app/model/user.js
然后书写数据库部分:
// app / model / user.js
'use strict';
module.exports = app => {
const { STRING, INTEGER, DATE , ENUM} = app.Sequelize;
// 配置(重要:一定要配置详细,一定要!!!)
const User = app.model.define('user', {
id: { type: INTEGER(20).UNSIGNED, primaryKey: true, autoIncrement: true },
username: { type: STRING(30), allowNull: false, defaultValue: '', comment: '用户名称', unique: true},
password: { type: STRING(200), allowNull: false, defaultValue: '' },
avatar_url: { type: STRING(200), allowNull: true, defaultValue: '' },
sex: { type: ENUM, values: ['男','女','保密'], allowNull: true, defaultValue: '男', comment: '用户性别'},
created_at: DATE,
updated_at: DATE
},{
timestamps: true, // 是否自动写入时间戳
tableName: 'user', // 自定义数据表名称
});
return User;
};
这个 Model 就可以在 Controller 和 Service 中通过 app.model.User
或者 ctx.model.User
访问到了,例如我们编写 app/controller/user.js
:这里我先写死数据,进行新增动作
// 创建用户
async create() {
const { ctx } = this;
// 写入数据库
let res = await this.app.model.User.create({
username:"测试",
password:'123456',
sex:"男"
});
ctx.body = res;
}
批量新增的操作:新增多个
async create() {
const { ctx } = this;
//批量新增数据库
let res = await this.app.model.User.bulkCreate([
{
username:"测试1",
password:'123456',
sex:"男"
},
{
username:"测试2",
password:'123456',
sex:"女"
}
]);
ctx.body = res;
}
然后执行后的结果如下:
2.数据库的查询:(单个和多个)
根据用户传递过来的id,来进行查询:
//读取用户数据
async read() {
const { ctx } = this;
//读取传递的参数
let id = parseInt(this.ctx.params.id);
//通过主键查询单个数据
let res = await this.app.model.User.findByPk(id);
ctx.body = {
msg: "ok",
data: res,
};
}
也可以通过where的条件查询:
//读取用户数据
async read() {
const { ctx } = this;
//读取传递的参数
let id = parseInt(this.ctx.params.id);
//根据条件查询
let res = await this.app.model.User.findOne({
where:{
id
}
});
ctx.body = {
msg: "ok",
data: res,
};
}
findAll:查询多个数据。findAndCountAll:查询多个并计数
如下:我们增加了where条件,对只有男的才查询,结果如下
async index() {
const { ctx } = this;
//查询列表数据
let result = [];
// 查询多个
result = await this.app.model.User.findAll({
where:{
sex:'男'
}
});
//拿到数据
ctx.body = {
msg: "ok",
data: result,
};
this.ctx.status = 200;
}
也可以进行模糊查询:这里需要注意的是op对象。其实对于这个,还是要很多操作可以书写的。
async index() {
const { ctx } = this;
//查询列表数据
let result = [];
// 查询多个
let Op = this.app.Sequelize.Op; //获取op对象
result = await this.app.model.User.findAll({
where:{
sex:'男',
username:{
[Op.like]:"%1%"
}
}
});
//拿到数据
ctx.body = {
msg: "ok",
data: result,
};
this.ctx.status = 200;
}
op对象的一些操作:
const Op = Sequelize.Op
[Op.and]: {a: 5} // 且 (a = 5)
[Op.or]: [{a: 5}, {a: 6}] // (a = 5 或 a = 6)
[Op.gt]: 6, // id > 6
[Op.gte]: 6, // id >= 6
[Op.lt]: 10, // id < 10
[Op.lte]: 10, // id <= 10
[Op.ne]: 20, // id != 20
[Op.eq]: 3, // = 3
[Op.not]: true, // 不是 TRUE
[Op.between]: [6, 10], // 在 6 和 10 之间
[Op.notBetween]: [11, 15], // 不在 11 和 15 之间
[Op.in]: [1, 2], // 在 [1, 2] 之中
[Op.notIn]: [1, 2], // 不在 [1, 2] 之中
[Op.like]: '%hat', // 包含 '%hat'
[Op.notLike]: '%hat' // 不包含 '%hat'
[Op.iLike]: '%hat' // 包含 '%hat' (不区分大小写) (仅限 PG)
[Op.notILike]: '%hat' // 不包含 '%hat' (仅限 PG)
[Op.startsWith]: 'hat' // 类似 'hat%'
[Op.endsWith]: 'hat' // 类似 '%hat'
[Op.substring]: 'hat' // 类似 '%hat%'
[Op.regexp]: '^[h|a|t]' // 匹配正则表达式/~ '^[h|a|t]' (仅限 MySQL/PG)
[Op.notRegexp]: '^[h|a|t]' // 不匹配正则表达式/!~ '^[h|a|t]' (仅限 MySQL/PG)
[Op.iRegexp]: '^[h|a|t]' // ~* '^[h|a|t]' (仅限 PG)
[Op.notIRegexp]: '^[h|a|t]' // !~* '^[h|a|t]' (仅限 PG)
[Op.like]: { [Op.any]: ['cat', 'hat']} // 包含任何数组['cat', 'hat'] - 同样适用于 iLike 和 notLike
[Op.overlap]: [1, 2] // && [1, 2] (PG数组重叠运算符)
[Op.contains]: [1, 2] // @> [1, 2] (PG数组包含运算符)
[Op.contained]: [1, 2] // <@ [1, 2] (PG数组包含于运算符)
[Op.any]: [2,3] // 任何数组[2, 3]::INTEGER (仅限PG)
[Op.col]: 'user.organization_id' // = 'user'.'organization_id', 使用数据库语言特定的列标识符, 本例使用 PG
当我们查询部分字段的值的时候,我们可以使用:attributes,来对字段筛选。order字段:来进行排序,
async index() {
const { ctx } = this;
//查询列表数据
let result = [];
// 查询多个
let Op = this.app.Sequelize.Op; //获取op对象
result = await this.app.model.User.findAll({
where:{
sex:'男'
},
attributes:['id','username','sex'],
order:[
['id','desc']
]
});
//拿到数据
ctx.body = {
msg: "ok",
data: result,
};
this.ctx.status = 200;
}
3.删除数据
async destroy(){
let id =this.ctx.params.id ? parseInt(this.ctx.params.id):0;
//查询出来数据
let res = await this.app.model.User.destroy({
where:{
id
}
});
this.ctx.body={
msg:'ok',
data:res
}
}
结果如下:第四条数据已经被删除
如果是批量删除,就可以在where内部传递条件来进行操作。
上述讲述的都是非常简单的操作,后续我会结合部分项目来进行更详细的介绍。