鍍金池/ 問(wèn)答/Java  數(shù)據(jù)庫(kù)  HTML/ koa+mysql,已實(shí)現(xiàn)批量刪除,請(qǐng)問(wèn)如何實(shí)現(xiàn)批量更新,批量插入,

koa+mysql,已實(shí)現(xiàn)批量刪除,請(qǐng)問(wèn)如何實(shí)現(xiàn)批量更新,批量插入,

問(wèn)題描述

koa+mysql,如何實(shí)現(xiàn)批量更新,批量插入,

已實(shí)現(xiàn)的批量刪除

clipboard.png

sql

// 根據(jù)id單個(gè)刪除
let cartDelectById = (id) => {
        let sql = `delete from cart where cart_id = ${id};`
        return query(sql)
    }
    // 根據(jù)id多個(gè)刪除
let cartDelectByIds = (ids) => {
    let sql = `delete from cart where cart_id in (${ids});`
    return query(sql)
}

koa

// 單個(gè)刪除
const cartDelectById = async(ctx) => {
        let id = 1;
        await cartModel.cartDelectById([id])
            .then(result => {
                ctx.body = {
                    state: 200,
                    msg: "刪除購(gòu)物車成功",
                    data: result
                }
            })
            .catch(error => {
                console.log(error);
                ctx.body = false;
            })
    }
// 多個(gè)刪除
const cartDelectByIds = async(ctx) => {
    let ids = [1, 2, 3];
    await cartModel.cartDelectByIds(ids)
        .then(result => {
            ctx.body = {
                state: 200,
                msg: "刪除購(gòu)物車成功",
                data: result
            }
        })
        .catch(error => {
            console.log(error);
            ctx.body = false;
        })
}

單條sql成功插入和更新,請(qǐng)問(wèn)如何實(shí)現(xiàn)批量更新,批量插入

// 插入
let cartInsertInto = (values) => {
    let sql = `insert into cart values(default,?,?,?,?,?);`
    return query(sql, values)
}
// 更新
let cartUpdate = (values) => {
    let sql = `update cart set user_id=?,goods_id=?,cart_goods_number=? where cart_id=?;`
    return query(sql)
}

插入

const cartInsertInto = async(ctx) => {
    console.log(ctx.request.body)
    let goodsId = ctx.request.body.goodsId;
    let cartGoodsNumber = ctx.request.body.goodsNumber;
    let userId = ctx.request.body.userId;
    await cartModel.cartInsertInto([userId, goodsId, cartGoodsNumber, new Date(), new Date()])
        .then(result => {
            ctx.body = {
                state: 200,
                msg: "插入購(gòu)物車成功",
                data: result
            }
        })
        .catch(error => {
            console.log(error);
            ctx.body = false;
        })
}
回答
編輯回答
執(zhí)念
let cartDelectById = (id) => {
    const sql = `delete from cart where cart_id in (${id.join(',')});`
    return query(sql)
}

這個(gè)函數(shù)改傳入數(shù)組即可。
注意:建議你的SQL加上SQL預(yù)處理機(jī)制防止SQL注入

2017年8月28日 02:36