Sequelize 查询操作

Sequelize 是一个基于 promise 的 Node.js ORM 工具, 目前支持 PostgresMySQLMariaDBSQLite 以及 Microsoft SQL Server. 它具有强大的事务支持, 关联关系, 预读和延迟加载,读取复制等功能

官网地址:Sequelize Docs 中文版 | sequelize-docs-Zh-CNSequelize 文档的中文版本: v4.42.0 v5.21.5 v6.6.2https://demopark.github.io/sequelize-docs-Zh-CN/

1、定义User的实体类

        'user' 对应的是表名
        id可以写也可以不写会有一个默认的id属性
        Sequelize+列类型
        db连接数据库的配置
        User.hasOne 说明是一对一的关联
                foreignKey 值是Sex的主键id
                sourceKey  值是User中的属性

const { Sequelize } = require('sequelize');
const db = require('../sequelizeConnectDb');
const Sex = require('./Sex');
let isSyncTable = false

const User = db.define('user', {  
  id: {
    type: Sequelize.UUID,
    defaultValue: Sequelize.UUIDV4,
    primaryKey: true
  },
  username: Sequelize.STRING,
  age: Sequelize.NUMBER,
  sexid: Sequelize.STRING,
  address: Sequelize.STRING
}, {
  timestamps: false,
  paranoid: false,
  underscored: true,
  freezeTableName: true,
  tableName: 'user'
})

User.hasOne(Sex, {
  foreignKey: 'id',
  sourceKey: 'sexid',
  constraints: false
});
if(isSyncTable) {
  User.sync({force: true})
}
module.exports = User

        定义一个Sex的实体类

const { Sequelize } = require('sequelize');
const db = require('../sequelizeConnectDb');
let isSyncTable = false

const Sex = db.define('sex', {
  name: Sequelize.STRING
}, {
  timestamps: false,
  paranoid: false,
  underscored: true,
  freezeTableName: true,
  tableName: 'sex'
})
if(isSyncTable) {
  Sex.sync({force: true})
}
module.exports = Sex

2、编写查询方法-获取全部数据不分页,主要用--User.findAll()来查询

const User = require('../model/User');
const express = require('express');

let router = express.Router();

/**
 * 查询列表,获取全部数据,不分页
 * 使用方法:findAll
 */
router.get('/userAllList', function (req, res, next) {
  User.findAll().then(resData => {
    res.send({
      code: 0,
      data: resData,
      msg: 'ok'
    })
  }).catch(() => {
    res.send({
      code: 9999,
      data: null,
      msg: '查询失败'
    })
  })
})
module.exports = router

3、编写查询方法-列表分页+关联表信息展示,主要用--User.findAndCountAll()来查询

/**
 * 查询列表,分页查询+关联查询性别名称
 * 使用方法:findAndCountAll
 * 在req.query中接受参数
 * 传参为:offset limit
 */
router.get('/userList', async function (req, res, next) {
  User.findAndCountAll({
    offset: (req.query.page - 1) * req.query.pageSize,
    limit: req.query.pageSize,
    include: [
      {
        model: Sex,
        attributes: [['name', 'sexname']]
      },
    ],
    distinct: true
  }).then(resData => {
    res.send({
      code: 0,
      data: resData,
      msg: 'ok'
    })
  }).catch((err) => {
    console.log(err);
    res.send({
      code: 9999,
      data: null,
      msg: '查询失败'
    })
  })
})
module.exports = router

4、编写查询方法-根据username查询为空就查询所有,主要用--User.findAndCountAll()来查询

const User = require('../model/User');
const express = require('express');
let router = express.Router();

/**
 * 查询详情,例如:根据username查询为空就查询所有
 * 使用方法:findAndCountAll
 * 在req.query中接受参数
 */
router.get('/userAll', async function (req, res, next) {
	let whereInfo = {};
	if(req.query.username){
		whereInfo={
		  username:req.query.username
		}
	}else{
		whereInfo={}
	}
	User.findAndCountAll({
	  where: whereInfo,
	}).then(resData => {
	  res.send({
		code: 0,
		data: resData,
		msg: 'ok'
	  })
	}).catch(() => {
	  res.send({
		code: 9999,
		data: null,
		msg: '查询失败'
	  })
	})
})
module.exports = router

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Sequelize是一个Node.js ORM(Object-Relational Mapping)框架,可以用来操作多种数据库,包括MySQL。下面是使用Sequelize操作MySQL数据库的基本步骤: 1. 安装Sequelize和MySQL驱动程序: ``` npm install --save sequelize mysql2 ``` 2. 创建Sequelize实例: ```javascript const Sequelize = require('sequelize'); const sequelize = new Sequelize('database', 'username', 'password', { host: 'localhost', dialect: 'mysql' }); ``` 其中,`database`是数据库名称,`username`和`password`是登录MySQL的用户名和密码,`localhost`是MySQL服务器地址,`dialect`指定数据库类型为MySQL。 3. 定义模型: ```javascript const User = sequelize.define('user', { id: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true }, name: { type: Sequelize.STRING }, age: { type: Sequelize.INTEGER } }); ``` 这里定义了一个名为`user`的模型,包含`id`、`name`和`age`三个字段。 4. 同步模型到数据库: ```javascript sequelize.sync() .then(() => { console.log('Database and tables created!'); }); ``` 这会在MySQL数据库中创建名为`user`的表。 5. 执行CRUD操作: ```javascript // 创建一条记录 User.create({ name: 'Alice', age: 25 }).then(user => { console.log(user.toJSON()); }); // 查询所有记录 User.findAll().then(users => { console.log(users.map(u => u.toJSON())); }); // 更新一条记录 User.update({ age: 26 }, { where: { name: 'Alice' } }).then(() => { console.log('Record updated!'); }); // 删除一条记录 User.destroy({ where: { name: 'Alice' } }).then(() => { console.log('Record deleted!'); }); ``` 这里演示了创建、查询、更新和删除操作。根据需要,可以使用更多Sequelize提供的方法来执行复杂的数据库操作

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值