【Node.js】Sequelize 操作 MySQL 数据库(数据查询)

1. findOne

findOne 方法用于根据条件查找单个记录。如果没有找到符合条件的记录,它将返回 null

User.findOne({
  where: {
    email: 'user@example.com'
  }
}).then(user => {
  if (user) {
    console.log('User found:', user);
  } else {
    console.log('No user found');
  }
});

2. findByPk

findByPk(Find By Primary Key)方法用于通过主键查找单个记录。你需要提供主键的值。

User.findByPk(1).then(user => {
  if (user) {
    console.log('User found:', user);
  } else {
    console.log('No user found');
  }
});

3. findAll

findAll 方法用于查找多个记录。你可以使用 where 来指定查询条件,order 来排序结果,limitoffset 来分页。

const { Op } = require('sequelize');

User.findAll({
  where: {
    name: {
      [Op.like]: '%John%' // 使用 Sequelize 的 Op 对象进行模糊查询
    }
  },
  order: [
    ['name', 'ASC'] // 按名字升序排序
  ],
  limit: 10, // 限制结果数量
  offset: 0 // 从第0条记录开始
}).then(users => {
  console.log('Users found:', users);
});

这里多提一嘴,Op 是一个提供操作符别名的对象。它允许你在查询条件中使用字符串形式的操作符,使得代码更易读和编写。Op 对象包含了一系列常用的操作符,比如 eq(等于)、ne(不等于)、gt(大于)、lt(小于)、like(模糊匹配)等。

分页查询:

User.finaAll({
    offset: (page - 1) * limit,
    limit: +limit,
})

4. count

count 方法用于获取满足特定条件的记录总数。

User.count({
  where: {
    isActive: true
  }
}).then(count => {
  console.log('Active users count:', count);
});

findAndCountAll 一边查分页数据,一边查总数。

User.findAndCountAll({
    where: {
        title: {
            [Op.like]: 'foo%'
        }
    },
    offset: 10,
    limit: 2
})

5. include

include 方法用于实现关联查询,例如当你需要同时获取用户及其关联的帖子时。

首先,定义模型之间的关联:

User.hasMany(Post); // 用户有多个帖子
Post.belongsTo(User); // 帖子属于一个用户

然后,使用 include 在查询中包含关联的数据:

User.findAll({
  include: [{
    model: Post,
    as: 'posts', // 指定别名,用于区分不同的关联
    where: {
      title: {
        [Op.like]: '%Important%' // 只查询标题包含 'Important' 的帖子
      }
    }
  }],
  where: {
    name: 'John Doe'
  }
}).then(users => {
  console.log('Users with posts:', users);
});

在这个示例中,我们查询了名字为 “John Doe” 的用户,并且包括了他们拥有的标题包含 “Important” 的帖子。

  • 10
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Sequelize是一个Node.js的ORM(Object-Relational Mapping)库,用于在Node.js环境中连接和操作关系数据库,其中也包括连接MySQL数据库。下面是使用Sequelize连接MySQL数据库的步骤: 1. 首先,需要确保已经在Node.js项目中安装了Sequelize库。可以通过在项目文件夹中运行以下命令来安装Sequelize: ``` npm install sequelize ``` 2. 接下来,在项目文件夹中创建一个用于连接数据库的配置文件,例如config.js。在该文件中,需要提供MySQL数据库的相关配置信息,包括数据库的名称、用户名、密码、主机和端口号等。以下是一个示例配置文件的代码: ```javascript module.exports = { development: { username: 'root', password: 'password', database: 'database', host: 'localhost', port: 3306, dialect: 'mysql' } }; ``` 3. 在项目的入口文件或者需要连接数据库的文件中,引入Sequelize库和先前创建的配置文件。然后,使用Sequelize构造函数创建一个数据库实例: ```javascript const Sequelize = require('sequelize'); const config = require('./config'); const sequelize = new Sequelize( config.development.database, config.development.username, config.development.password, { host: config.development.host, port: config.development.port, dialect: config.development.dialect } ); ``` 4. 现在,可以使用sequelize对象进行数据库操作,如定义模型、创建表格和查询数据等。以下是一个创建示例模型并同步数据库的代码片段: ```javascript const User = sequelize.define('User', { firstName: { type: Sequelize.STRING, allowNull: false }, lastName: { type: Sequelize.STRING, allowNull: false } }); sequelize.sync({ force: true }) // force: true会删除已存在的表 .then(() => { console.log('Database synchronized'); }) .catch((error) => { console.error('Unable to synchronize database:', error); }); ``` 在上述代码中,定义了一个名为User的模型,包含了firstName和lastName两个字段。然后,使用sequelize.sync()方法同步数据库并创建对应的表格。 通过以上步骤,就可以成功使用Sequelize连接MySQL数据库并进行相关操作。当然,这只是一个简单的示例,Sequelize还提供了更多强大的功能,例如数据关联、查询过滤和事务管理等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小秀_heo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值