Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.8k views
in Technique[技术] by (71.8m points)

nodejs如何多条件查询?

一个列表接口,目前是这样写 我感觉我要疯了,求优化方案

router.post('/list', (req, res) => {
    let params = req.body;
    // SQL
    let sql = `
        SELECT 
            *
        FROM 
            content
    `;
    if(params.cityId){
        sql = sql + ` WHERE cityId='${params.cityId}'`;
        // 县
        if(params.regionId){
            sql = sql + ` and regionId='${params.regionId}'`;
        }
        // 按时间
        if(params.filter == '1'){
            sql = sql + ` order by modifTime ${params.order}`;
        }
        // 按点赞
        if(params.filter == '2'){
            sql = sql + ` order by zan ${params.order}`;
        }
        // 按收藏
        if(params.filter == '3'){
            sql = sql + ` order by collect ${params.order}`;
        }
        // 按评论
        if(params.filter == '4'){
            sql = sql + ` order by commentNum ${params.order}`;
        }
        // 按价格
        if(params.filter == '5'){
            sql = sql + ` order by price ${params.order}`;
        }
        // 分页
        let pageSize = 20;
        let pageNum = (params.pageNum -1)*pageSize;
        sql = sql + ` limit ${pageNum},${pageSize}`;
    }
    // 执行
    $db.query(sql)
    .then(data=>{
        // 返回给前端
        res.json({
            code:200,
            msg:"操作成功",
            data:data
        });
        res.end();
    })
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

我的天。。。。这个竟然不考虑用ORM


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...