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)
    })
}

Last updated