Node.js中关于Sequelize使用方法---Orm框架 [TOC]

本文详细介绍了如何使用SequelizeORM框架进行JavaScript项目的数据库操作,包括安装依赖、初始化项目、创建数据库表、数据填充、以及基础的增删改查功能。
摘要由CSDN通过智能技术生成

Sequelize使用方法—Orm框架

1.使用前需要安装的依赖

npm install sequelize -S
npm install mysql2 -S

为了更好的使用Sequelize,官方提供相关的脚手架cli

npm install sequelize-cli -g

2.初始化Sequelize项目

sequelize init

会在当前项目中生成

  • config: 数据库配置
  • migrations:迁移
  • models:模型
  • seeders: 种子

3.初始化数据库

sequelize db:create --charset 'utf8mb4'

数据库是根据config文件夹下的config.json中的database字段创建的

{
  "development": {
    "username": "root",
    "password": "root",
    "database": "ai_express_development",
    "host": "127.0.0.1",
    "dialect": "mysql"
}

4.创建表

使用代码来创建表需要用到models模型,而创建模型的时候会自动生成一份migrations迁移文件

sequelize model:generate --name program_name --attributes field1:type,field2:type

示例代码:

sequelize model:generate --name Article --attributes title:string,content:text

生成出的article.js的模型文件,目前项目需求简单,保持不动就好,到时候可直接使用

之后打开migrations迁移文件中的 create-article.js, 里面保存的都是Article的字段

'use strict';
/** @type {import('sequelize-cli').Migration} */
module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.createTable('Articles', {
      id: {
        allowNull: false,//不为空
        autoIncrement: true, //自增
        primaryKey: true,//主键
        type: Sequelize.INTEGER//数字类型
      },
      title: {
        type: Sequelize.STRING
      },
      content: {
        type: Sequelize.TEXT
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  async down(queryInterface, Sequelize) {
    await queryInterface.dropTable('Articles');
  }
};

里面除了titlecontent以外,还自动生成了id,createAt,updateAt,而这三个字段会自动填充

执行此命令可运行 create-article.js迁移文件,会自动将该表创建至数据库中

sequelize db:migrate

5.将测试数据填充到表

需要用到seed种子文件,执行命令即可创建

sequelize seed:generate --name table_name

点开此种子文件,将 bulkInsert()以及bulkDelete()里的表名换成自己创建的表的名字,在数组里加上对应字段的对象

'use strict';

/** @type {import('sequelize-cli').Migration} */
module.exports = {
  async up (queryInterface, Sequelize) {
      await queryInterface.bulkInsert('Article', [{
        title: '今天天气可真好啊',
        content:"狂风暴雨特别凉快哦,欢迎每年来武汉看海! ",
        createdAt: new Date(),
        updatedAt: new Date()
      },{
        title: '武汉最好吃的小吃是什么',
        content:"狂风暴雨特别凉快哦,欢迎每年来武汉看海! ",
        createdAt: new Date(),
        updatedAt: new Date()
      }], {});
  },

  async down (queryInterface, Sequelize) {
      await queryInterface.bulkDelete('Article', null, {});
  }
};

执行此命令即可将测试数据填充至对应表中

sequelize db:seed:all

6.增删改查

在routes或者services中 引入model文件

const models = require('../models')

models.xxx 一定是在models文件夹下的模型的名字

6.1查

6.1.1查询所有
const data = await models.Article.findAll()
6.1.2模糊查询

引入Op

const Op = models.Sequelize.Op

需要给findAll()方法中传入一个对象,需要在此对象里添加where字段,where字段需要接收一个对象

let where = {}

where.title = {
    [Op.like]: '%' + title + '%'
}

const data = await models.Article.findAll({
    where:where
})
6.1.3根据id查询

findByPk()中的Pk是主键的意思,默认为id

const data = await models.Article.findByPk(id)

6.2增

6.2.1增加
const data = await models.Article.create({
    title:"标题",
    content:"详情"
})

6.3改

6.3.1根据id修改表
const data = await models.Article.findByPk(id)
data.update(req.body) //将前端传过来的数据进行修改

6.4删

6.4.1根据id删除表
const data = await models.Article.findByPk(id)
data.destory()
  • 18
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值