其他分享
首页 > 其他分享> > Sequelize-查询/修改/删除-5

Sequelize-查询/修改/删除-5

作者:互联网

查询

根据ID查询

 1 User.findByPk(1)
 2   .then(response => {
 3     console.log(response.dataValues);
 4     /**
 5      {
 6         id: 1,
 7         name: 'ls',
 8         age: 88,
 9         gender: '男',
10         createdAt: 2021-10-31T12:39:16.000Z,
11         updatedAt: 2021-10-31T12:39:16.000Z
12       }
13      */
14   })

查询所有数据

1 User.findAll()
2   .then(response => {
3     console.log(response);
4   });

查询所有数据并拿到某几个字段

1 User.findAll({
2   attributes: ['name', 'age'], // 只需要name和age字段
3 })
4   .then(response => {
5     console.log(response);
6   });

条件查询

 1 User.findAll({
 2   where: { // 条件查询
 3     age: { // age字段
 4       [Sequelize.Op.gte]: 20, // 大于等于20
 5     }
 6   }
 7 })
 8   .then(response => {
 9     console.log(response);
10   });

条件查询OR

 1 User.findAll({
 2   where: { // 条件查询
 3     [Sequelize.Op.or]: { // OR
 4       age: 18, // 满足一个即可
 5       id: 1, // 满足一个即可
 6     }
 7   }
 8 })
 9   .then(response => {
10     console.log(response);
11   });

分页查询

1 User.findAll({
2   offset: 1, // 跳过一条数据
3   limit: 1, // 显示一条数据
4 }).then(response => {
5   console.log(response.length); // 1
6 });

排序查询

1 User.findAll({
2   order: [ // 排序
3     ['id', 'desc'], // 以id字段降序排序
4   ]
5 }).then(response => {
6   console.log(response);
7 })

 

修改

 1 User.findByPk(1)
 2   .then(async response => {
 3     response.name = 'lisi';
 4     const u = await response.save();
 5     console.log(u.dataValues);
 6     /**
 7      {
 8         id: 1,
 9         name: 'lisi',
10         age: 88,
11         gender: '男',
12         createdAt: 2021-10-31T12:39:16.000Z,
13         updatedAt: 2021-10-31T12:49:24.839Z
14      }
15      */
16   });
1 User.update({ // 修改内容
2   name: 'lisi'
3 }, {
4   where: { // 条件
5     id: 1
6   }
7 }).then(response => {
8   console.log('成功修改'); // 成功修改
9 })

删除

1 User.destroy({
2   where: { // 删除条件
3     id: 1
4   }
5 }).then(response => {
6   console.log('删除成功', response); // 删除成功 1
7 })

 

标签:10,console,log,删除,查询,User,Sequelize,response
来源: https://www.cnblogs.com/xiebenyin-/p/15490927.html