> For the complete documentation index, see [llms.txt](https://yicoding.gitbook.io/wechat/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://yicoding.gitbook.io/wechat/yun-kai-fa/knex.js-cha-xun-shu-ju-ku.md).

# knex.js查询数据库

## 1.get请求

```
const { mysql } = require('../qcloud')
// 按照openid查找收藏列表
async function collectFindByOpenId(ctx, next) {
    await mysql('songlist').
    join('collect', 'songlist.id', '=', 'collect.songid').
    select('*').
    where({
        openid: ctx.query.openid
    }).
    then(res => {
        ctx.state.code = 0
        ctx.state.data = res
    }).catch(err => {
        ctx.state.code = -1
        throw new Error(err)
    })
}
module.exports = {
    collectFindByOpenId
}
```

## 2.post请求

```
// 添加收藏
async function addCollect(ctx, next) {
    await mysql('collect').
    insert({
        openid: ctx.request.body.openid,
        songid: ctx.request.body.id
    }).then(res => {
        ctx.state.code = 0
        ctx.state.data = res
    }).catch(err => {
        ctx.state.code = -1
        throw new Error(err)
    })
}
```

## 3.delete请求

```
// 取消收藏
async function removeCollect(ctx, next) {
    await mysql('collect').where({
        openid: ctx.request.body.openid,
        songid: ctx.request.body.id
    }).del().then(res => {
        ctx.state.code = 0
        ctx.state.data = res
    }).catch(err => {
        ctx.state.code = -1
        throw new Error(err)
    })
}
```

## 4.put请求

```
// 设为已读
async function alterMsg(ctx, next) {
    await mysql('times_rate').
    where({
        id: ctx.request.body.id
    }).
    update({
        isRead: true
    }).then(res => {
        ctx.state.code = 0
        ctx.state.data = res
    }).catch(err => {
        ctx.state.code = -1
        throw new Error(err)
    })
}
```
