收藏
回答

动态的SQL语句在云函数中如何使用?

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

{
        _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 个回答

  • 金煜峰
    金煜峰
    2019-11-04
    data: {
      ['roomList.' + index1 + '.bedList.' + index2 + '.isChoose']: 1
    },

    或者

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


    2019-11-04
    有用 1
    回复 1
    • ୯昊森先生୬
      ୯昊森先生୬
      2019-11-04
      谢谢大佬,已解决
      2019-11-04
      回复
登录 后发表内容
问题标签