//数据库 user
{
uid: 666,
name: "柚子",
lv: 10,
group: 888
},
{
......
}
// GetUserInfo.js
GetUI(o){
let uid = Number(o.uid) || [] // 666
let name = o.name || [] // '柚子'
let lv = Number(o.lv) || [] // 空
let group = o.group || [] // 空
// group & lv 为空时
if (group == '' && lv == '') {
db.collection('user')
.where({
uid: _.in(uid), // 筛id
name: _.in(name) // 筛名字
})
.get()
.then(res => {
console.log("返回:", res.data)
})
.catch(err => {
console.log("错误:", err);
})
} else if (group != '' && lv == '') { //group不为空 & lv 为空时
db.collection('user')
.where({
uid: _.in(uid), // 筛id
name: _.in(name), // 筛名
group: _.in(group) // 筛组
})
.get()
.then(res => {
console.log("返回:", res.data)
})
.catch(err => {
console.log("错误:", err);
})
} else if (group == '' && lv != '') { //group为空 & lv 不为空时
db.collection('user')
.where({
uid: _.in(uid), // 筛id
name: _.in(name), // 筛名
lv: _.in(lv) // 筛级
})
.get()
.then(res => {
console.log("返回:", res.data)
})
.catch(err => {
console.log("错误:", err);
})
}
}
.where{} 参数值为空时,查询不到数据~
https://developers.weixin.qq.com/miniprogram/dev/wxcloud/guide/database/dbscript.html
文档说不支持各种表达式,.......
我不想写这么多if else......
有什么办法能不写N个if else???
感谢~
网友回复
o0o有脾气的酸奶:
其实写if else 也没事,反倒代码比较容易看懂
也可以写得很简洁,也可以不用写那么多let,但是前提示会用还要看得懂,让别人也看得懂
async GetUI(o){
let res = [],wh = {}, isEmptyWhere = !0,
{ uid = !1, name = !1, lv = !1, group = !1 } = o || {}, arrInit
try{
arrInit = (o, type)=>(!Array.isArray(o) && (o = [o]), o.map(v=>type?type(v):v))
lv && (wh.lv = _.in(arrInit(lv, Number)))
uid && (wh.uid = _.in(arrInit(uid, Number)))
name && (wh.name = _.in(arrInit(name, String)))
group && (wh.group = _.in(arrInit(group, String)))
// 查询条件是否为为空
isEmptyWhere = JSON.stringify(wh) != '{}'
res = isEmptyWhere ? {} : await db.collection('user').where(wh).get()
res = res.data ? res.data : []
console.log("返回:", res)
}catch(e){
console.log("错误:", e)
}
return res
}
若认为该回答有用,给回答者点个[ 有用 ],让答案帮助更多的人
stop eating:
只需要组装where condition就行了