动态的SQL语句在云函数中如何使用?
发布于 8 年前 作者 min75 10290 次浏览 来自 官方Issues

这是我的云数据库中一个集合的数据

{
        _id: 'west01',
        name: '西学楼1号',
        roomList: [
          {
            room:'101',
            bedList:[
              {bed:'A',isChoose:0},
              {bed:'B',isChoose:0},
              {bed:'C',isChoose:0},
              {bed:'D',isChoose:1},
            ]
          },
          {
            room:'102',
            bedList:[
              {bed:'A',isChoose:0},
              {bed:'B',isChoose:0},
              {bed:'C',isChoose:1},
              {bed:'D',isChoose:1},
            ]
          },
          {
            room:'103',
            bedList:[
              {bed:'A',isChoose:0},
              {bed:'B',isChoose:0},
              {bed:'C',isChoose:0},
              {bed:'D',isChoose:0},
            ]
          }
        ],
      },
      {
        _id: 'west02',
        name: '西学楼2号',
        roomList: [
          {
            room:'201',
            bedList:[
              {bed:'A',isChoose:0},
              {bed:'B',isChoose:0},
              {bed:'C',isChoose:0},
              {bed:'D',isChoose:1},
            ]
          },
          {
            room:'202',
            bedList:[
              {bed:'A',isChoose:1},
              {bed:'B',isChoose:0},
              {bed:'C',isChoose:1},
              {bed:'D',isChoose:0},
            ]
          }
        ],
      }

想通过小程序来选择宿舍,通过云函数来将某个被选定的床位的“isChoose”字段设置为1。

例如,我选择了“西学楼1号-101房-A床”,那么我就需要把对应的床位的“isChoose”字段设置为1

我的json数据是多层的,于是我在云开发控制台的模板中尝试修改,我的方案是,通过下面的代码去修改“isChoose”字段的值

db.collection('dormitories')
  .where({
    name: '西学楼1号'
  })
  .update({
    data: {
      'roomList.0.bedList.0.isChoose': 1
    },
  })

但是我也面临着一个问题,选择其他宿舍的话,那’roomList.0.bedList.0.isChoose’里的两个“0”(房间号的index和床号的index)就是动态的,而我也可以获得这两个index值,可是eval()在小程序中用不了,于是我也不能动态地改变这个SQL语句。

各位大佬有解决方案,或者其他的实现方案么?请不吝赐教,谢谢

1 回复
data: {
  ['roomList.' + index1 + '.bedList.' + index2 + '.isChoose']: 1
},

或者

data: {
  [`roomList.${index1}.bedList.${index2}.isChoose`]: 1
},
回到顶部