koa+Sequelize进行get,post,delete,put,all操作

山水有轻音 2021-02-22 PM 1223℃ 1条

koa如何进行常见请求操作

1.get传值接受

请求参数放在 URL 后面

url = 'http://localhost:3000/home?id=12&name=ikcamp'
router.get("/admin/get", async (ctx) => {
          let ctx_query = ctx.query;
          console.log("99", ctx_query); --{ id: '12', name: 'ikcamp' }
})

url后面跟一个单独的参数

url = 'http://localhost:3000/home/12'
router.get("/users/:id", async (ctx) => {
        console.log(ctx.params) ---{ id: '12' }
        //const { id } = ctx.params
        ctx.body = `获取id为${id}的用户`;
})

请求参数放在 URL 中间

url = 'http://localhost:3000/home/12/ikcamp'
// 增加如下代码
router.get('/home/:id/:name', async(ctx, next)=>{
    console.log(ctx.params) -- { id: '12', name: 'ikcamp' }

})

2.post传值接受

安装 koa-bodyparser

npm install koa-bodyparser --save

使用
const bodyParser = require("koa-bodyparser");

const app = new Koa();
app.use(bodyParser()); --要在路由之前加入
const router = new Router();
请求参数在body之中
如
router.post("/admin/pot", async (ctx) => {
  let query = ctx.request.body; --接受post传值;
  console.log("99", ctx_query);

})

3.detel传值接受

router.del("/test/deleate", async (ctx, next) => {
  let query = ctx.query;  --获取传的数值
})

router.del("/users/:id", async (ctx) => {
   const { id } = ctx.params
   ctx.body = `删除id为${id}的用户`;
        })

4.put传值接受

router.put("/users/:id", async (ctx) => {
    const { id } = ctx.params
    ctx.body = `修改id为${id}的用户`;
})

5. all请求传值--会匹配所有的请求方式

router.all("/users/:id", async (ctx) => {
    ctx.body = ctx.params;
});

koa使用Sequelize操作数据库

如何进行分页查询

1、分页模糊精准查询

const Sequelize = require("sequelize");
const Op = Sequelize.Op;
const blogPageList = await Blog.findAll({
    order: [
      ['id', 'desc']                     --通过哪些字段排序
    ],
    where:{
    userId: 1,                 --精准查询
    brand: {  //brand模糊查询的字段
       [Op.like]: `%${keyword}%`   --模糊查询
        }
    },
    limit: pageSize,                  --每页限制多少条
    offset: (currentPage-1)*pageSize     --从多少开始
  })

2、联表查询

const { User, Blog } = require('./model')
const blogListWithUser = await Blog.findAndCountAll({
    order: [
      ['id', 'desc']
    ],
    include: [                              --包含联表查询的信息
      {
        model: User,
        attributes: ['userName', 'nickName'],
        where: {
          userName: 'zj'
        }
      }
    ]
  })

  console.log('blogListWithUser: ',
  blogListWithUser.count,
  blogListWithUser.rows.map(blog => {
    const blogVal = blog.dataValues
    blogVal.user = blogVal.user.dataValues
    return blogVal
  })
  )

3、联表查询2

  const userListWithBlog = await User.findAndCountAll({
    attributes: ['userName', 'nickName'],
    include: [
      {
        model: Blog
      }
    ]
  })
  console.log('userListWithBlog: ',
  userListWithBlog.count,
  userListWithBlog.rows.map(user => {
    const userVal = user.dataValues
    userVal.blogs = userVal.blogs.map(blog => blog.dataValues)
    return userVal
  })
  )

Sequelize.Op操作符

Sequelize 可用于创建更复杂比较的符号运算符 -

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 <= 10
[Op.ne]: 20,               // id != 20
[Op.eq]: 3,                // = 3
[Op.not]: true,            // 不是 TRUE
[Op.between]: [6, 10],     // 在 6 和 10 之间
[Op.notBetween]: [11, 15], // 不在 11 和 15 之间
[Op.in]: [1, 2],           // 在 [1, 2] 之中
[Op.notIn]: [1, 2],        // 不在 [1, 2] 之中
[Op.like]: '%hat',         // 包含 '%hat'
[Op.notLike]: '%hat'       // 不包含 '%hat'
[Op.iLike]: '%hat'         // 包含 '%hat' (不区分大小写)  (仅限 PG)
[Op.notILike]: '%hat'      // 不包含 '%hat'  (仅限 PG)
[Op.regexp]: '^[h|a|t]'    // 匹配正则表达式/~ '^[h|a|t]' (仅限 MySQL/PG)
[Op.notRegexp]: '^[h|a|t]' // 不匹配正则表达式/!~ '^[h|a|t]' (仅限 MySQL/PG)
[Op.iRegexp]: '^[h|a|t]'    // ~* '^[h|a|t]' (仅限 PG)
[Op.notIRegexp]: '^[h|a|t]' // !~* '^[h|a|t]' (仅限 PG)
[Op.like]: { [Op.any]: ['cat', 'hat']} // 包含任何数组['cat', 'hat'] - 同样适用于 iLike 和 notLike
[Op.overlap]: [1, 2]       // && [1, 2] (PG数组重叠运算符)
[Op.contains]: [1, 2]      // @> [1, 2] (PG数组包含运算符)
[Op.contained]: [1, 2]     // <@ [1, 2] (PG数组包含于运算符)
[Op.any]: [2,3]            // 任何数组[2, 3]::INTEGER (仅限PG)

[Op.col]: 'user.organization_id' // = 'user'.'organization_id', 使用数据库语言特定的列标识符, 本例使用 PG
标签: koa, sql

非特殊说明,本博所有文章均为博主原创。

评论啦~



唉呀 ~ 仅有一条评论


  1. 山水有轻音
    山水有轻音 博主

    很不错,楼主加油

    回复 2021-02-22 14:43