小程序云开发lookup联表查询右表添加查询条件

 all_course表结构:【课程基础表】

 rel_stu_course表结构:【学生课程关联表】

 

 需求:查询stuId:79550af260c865f11f9c9dde70e18f4c 对应的课程报名节数

用scrollview做了查询的分页弹窗,滚动下拉,页容量为100。预计一页就够了。。。。。。

写在了云函数里,pagelist:其中有多个页面的分页查询,有加条件的不加条件的,第一次写,也不知道如何优化结构,代码就冗余着能用就好了。。为啥分页都写在一个云函数里,因为用的免费版,免费版的云函数上限是十个。。。坑。。。我觉得就用一个云函数就行了,,当成controller,定义好统一的参数和返回值,加各种判断和逻辑。。。。。。。

total =  (await  db.collection('all_course').aggregate()
      .lookup({
        from: 'rel_stu_course',
        let: {
          course_name: '$name',
          stuId:event.stuId,
        },
         pipeline: $.pipeline()
          .match(_.expr($.and([
          $.eq(['$name', '$$course_name']),
          $.eq(['$stuId', '$$stuId']),
        ])))
        .project({
              _id: 0,
              stuId: 1,
              name:1,
              count: 1,
            })
            .done(),
          as: 'stus',
        })
      .count('count')
      .end()).list[0].count;//总数
 list = (await db.collection('all_course').aggregate()
      .lookup({
        from: 'rel_stu_course',
        let: {
          course_name: '$name',
          stuId:event.stuId,
        },
         pipeline: $.pipeline()
          .match(_.expr($.and([
          $.eq(['$name', '$$course_name']),
          $.eq(['$stuId', '$$stuId']),
        ])))
        .project({
              _id: 0,
              stuId: 1,
              name:1,
              count: 1,
            })
            .done(),
          as: 'stus',
        })
        .skip((event.page - 1) * event.pageSize) 
        .limit(event.pageSize) 
      .end()).list

 小程序lookup代表left join,

pipeline发现可以筛选右表rel_stu_course的数据,网上查询到的都是pipeline里条件都是主表的条件 即all_course表,又看了一遍小程序的示例,根据最后一个lookup的给每个记录关联上子查询即相同的数据条目,改了改适用,完美解决右表加条件的需求!!!

官方示例链接:滑到最下面的例子【拼接被连接集合的子查询】稍微改改就好了

https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-sdk-api/database/aggregate/Aggregate.lookup.html#%E7%A4%BA%E4%BE%8B

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值