Multi-table joint search of WeChat applet cloud development (cloud database, cloud function)

       Today I am writing a WeChat mini-program demo, using cloud development, which is a process for a laboratory appointment. I was very happy to write at the beginning, after all, using java ssm + mysql a simple stroke. I thought about the cloud database. But then I found that the gap was quite big, but fortunately, as long as you are proficient in the database, you can still easily get started by looking at the API documentation for this. However, it seems that Du Niang and the small program cloud development community have little specific use of this multi-table joint check. The API documentation is actually relatively difficult for novices, and it is difficult to find teaching, so I will explain here. Not much nonsense, code.

I have a total of three tables: user table, laboratory table, approval table

The data of the user table is like this:

{
    "_id":"f149f6775e9d6ec600876c1a16ced8c8", //这个是云数据库自动生成的id
    "u_account":"asd",
    "u_name":"学生1",
    "u_password":"123",
    "u_role":0
}

My laboratory table looks like this:

{
    "_id":"0d9cdb685e9d8354007a2b0e376d0d73",
    "l_name":"实验室C",
    "l_manager":"负责人3",
    "l_address":"教学楼C202",
    "l_status":"可预约"
}

My approval form looks like this:

{
    "_id":"f149f6775e9dabd10090e4d452807018",
    "u_account":"asd",
    "l_id":"0d9cdb685e9d8354007a2b0e376d0d73",
    "a_status":"待审核",
    "a_date":"2020-04-18 20:59"
}

The next step is to hope that the three tables will be jointly checked and the fields will be merged.

1. First look at the two tables

The official documentation of the applet is very clear, and I want to use aggregation for joint investigation

API address:  https://developers.weixin.qq.com/miniprogram/dev/wxcloud/guide/database/join.html

2. First check the approval form and user form

// 云函数入口函数
exports.main = async (event, context) => {
  return cloud.database().collection("tb_approval").aggregate() //选择我的审批表
          .lookup({
            from:"tb_user", //把tb_user用户表关联上
            localField: 'u_account', //审批表的关联字段
            foreignField: 'u_account', //用户表的关联字段
            as: 'uapproval' //匹配的结果作为uapproval相当于起个别名
          }).end({
            success:function(res){
              return res;
            },
            fail(error) {
              return error;
            }
          })
}

The output is like this:

{
    _id:"f149f6775e9dabd10090e4d452807018",
    u_account:"asd",
    l_id:"0d9cdb685e9d8354007a2b0e376d0d73",
    a_status:"待审核",
    a_date:"2020-04-18 20:59",
    uapproval:[
        {
            _id:"f149f6775e9d6ec600876c1a16ced8c8",
            u_account:"asd",
            u_name:"学生1",
            u_password:"123",
            u_role:0
        }
    ]
}

3. Modify the return result

Now, it ’s not from the joint investigation. Do n’t worry, I know this is not what you want. What you want is this:

{
    _id:"f149f6775e9dabd10090e4d452807018",
    u_account:"asd",
    l_id:"0d9cdb685e9d8354007a2b0e376d0d73",
    a_status:"待审核",
    a_date:"2020-04-18 20:59",
    u_name:"学生1",
    u_password:"123",
    u_role:0
}

How to do it, you need to use replaceRoot, newRoot, project. The usage of these three looks at the API yourself

Changing the cloud function to this will have the above effect

var $ = cloud.database().command.aggregate   //定义聚合操作符
// 云函数入口函数
exports.main = async (event, context) => {
  return cloud.database().collection("tb_approval").aggregate()
          .lookup({
            from:"tb_user",
            localField: 'u_account',
            foreignField: 'u_account',
            as: 'uapproval'
          })
          .replaceRoot({  

            //replaceRoot指定一个已有字段作为输出的根节点,也可以指定一个计算出的新字段作为根节点。
           //newRoot  代表新的根节点

            newRoot: $.mergeObjects([$.arrayElemAt(['$uapproval', 0]), '$$ROOT'])
            
            //mergeObjects 累计器操作符
            //$.mergeObjects([params1,params2...]) 可以合并多个元素
            //$.arrayElemAt(['$uapproval', 0]), '$$ROOT']
            //就是取uapproval数组的第一个元素,与原始的根融合在一起
            
          })
          .project({
            //project把指定的字段传递给下一个流水线,指定的字段可以是某个已经存在的字段,也可以是计算出来的新字段
            uapproval: 0
          })
          .end({
            success:function(res){
              return res;
            },
            fail(error) {
              return error;
            }
          })
}

This will return the data as above. But here is just a joint check of the two tables. Don't worry, the three watches are released

4. Three-table joint inspection

var $ = cloud.database().command.aggregate
// 云函数入口函数
exports.main = async (event, context) => {
  return cloud.database().collection("tb_approval").aggregate()
    .lookup({
      from: "tb_user",
      localField: 'u_account',
      foreignField: 'u_account',
      as: 'uapproval'
    })
    .lookup({
      from: "tb_lab",
      localField: 'l_id',
      foreignField: '_id',
      as: 'lapproval'
    })
    .replaceRoot({
      newRoot: $.mergeObjects([$.arrayElemAt(['$uapproval', 0]), $.arrayElemAt(['$lapproval', 0]), '$$ROOT'])
    })
    .project({
      uapproval: 0,
      lapproval: 0
    })
    .end({
      success: function (res) {
        return res;
      },
      fail(error) {
        return error;
      }
    })
}

The data returned is this:

{
    _id:"f149f6775e9dabd10090e4d452807018",
    u_account:"asd",
    u_name:"学生1",
    u_password:"123",
    u_role:0,
    l_id:"0d9cdb685e9d8354007a2b0e376d0d73",
    l_name:"实验室C"
    l_address:"教学楼C202",
    l_manager:"负责人3",
    l_status:"可预约",
    a_status:"待审核",
    a_date:"2020-04-18 20:59"
}

In this way, the joint check of the three tables is understood. In this case, more of the table is not a breeze. Seeing that no one has ever posted such an explanation blog, so I post one so that others will avoid detours.

 

My personal original, if there is any similarity, is purely coincidental, or contact me to make changes. Please reprint or CV combination indicate the source, thank you! (If you have any questions or errors, please point out, I QQ: 752231513)

Published 20 original articles · praised 45 · views 100,000+

Guess you like

Origin blog.csdn.net/qq_30548105/article/details/105647358