egg数据库操作(增删改查)

您所在的位置:网站首页 vue3d模型用什么做 egg数据库操作(增删改查)

egg数据库操作(增删改查)

2023-07-30 11:33| 来源: 网络整理| 查看: 265

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 [1, 2] (PG数组包含运算符) [Op.contained]: [1, 2] //


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3