使用场景

通常在复杂的查询中都会用到where语句,自然各条件可能传可能不传值,如下

function createSql(search,state) {
        let sql = ''
        if (search !== undefined && state === undefined) {
            sql = `where remark LIKE '%${search}%'`
        }else if (search === undefined && state !== undefined) {
            sql = `where state=${state}`
        }else if (search !== undefined && state !== undefined) {
            sql = `where remark LIKE '%${search}%' and state=${state}`
        }
        return sql
    }
  • 示例:
createSql('关键',0)
=> "where remark LIKE '%关键%' and state=0"

封装成工具函数

1. 参数全为undefined
2. 参数个数不限制

const createwhere = (arr) => {
let _isFirst = true
const _sql = arr.map((it,idx) => {
    const _key = Object.keys(it)[0]
    const _value = Object.values(it)[0]
    if(_value===undefined) return
    if(_isFirst){
    _isFirst = false
    return `where ${_key} = '${_value}'`
    }
    return `and ${_key} = '${_value}'`
})
console.log(_sql.join(' '))
return _sql.join(' ')
}
  • 示例:
const val1 = 'test'
const val2 = '0'
const val3 = undefined
createwhere([{name:val1},{remark:val2},{key:val3}])
=> where name = 'test' and remark = '11'