微信小程序云数据库where查询语句字段名和字段值都可以是变量
想要实现的功能
界面代码
// An highlighted block
<view class="team_button">
<view bindtap="team_add" class="button_a">添加队员</view>
<view bindtap="team_search" class="button_a">查找队员</view>
<view class="team_search">
<input type="text" placeholder="请输入姓名或学号" bindinput="get_search"/>
</view>
</view>
输入字符或数字进行查询小程序云数据库,展示内容
遇到的问题
拟采取对调用全局函数Number() 对输入框内容进行强制转换成数字型,如果可以转化成功,就对stu_id(学号)字段进行查询,转化不成功就对name(姓名)字段进行查询
遇到问题
let search_thing1=Number(that.data.search_thing)
if(!search_thing1){
search='name'
}else{
search='stu_id'
}
db.collection('team').where({
//name:'xxx'
// search:that.data.search_thing
[search] : that.data.search_thing
})
.get()
首先查询name:’xxx’是可以查询到的,但是查询search:’xxx’就是查不到。
解决
研究半天发现,查询字段内容可以是变量和字符串,但是查询字段如果为变量时需要加上[],对[search] : that.data.search_thing查询就成功了
js代码
team_search(e){
let that=this
let search= ""
let search_thing1=Number(that.data.search_thing)
if(!search_thing1){
search='name'
}else{
search='stu_id'
}
console.log(search,that.data.search_thing) //输出语句
db.collection('team').where({
// name:'xxx'
// search:that.data.search_thing
[search] : that.data.search_thing
})
.get().then(res=>{
wx.showToast({
title: '查找成功',
duration:1000,
})
console.log(res.data)
that.setData({
team_list:res.data
})
}).catch(res=>{
wx.showToast({
title: '查找失败',
duration:1000,
})
})
},