-
需求
三个表,图片表(picture)、套装表(pictureSet),套装图片关联关系表(pictureSetRelationShip)
- 图片表(picture)表数据
- 套装表
- 关联关系表
关系表中存在多条记录,一个setId可能会有多个pictureID与之对应,如下
- 期望得到的结果
即希望能够得到一个套装下包含多个picture
{"list":[{"_id":"setName","tzitemPictureList":[
[{"_id":"f18e14fa6524ee6801cd6cd2d","bh":"ceshitaozhuang","detailUrl":"cloud://wanyfbgkybgsvd882fb24-1319293858/1696919142576-450648328.png","jxfl":"玄关/客厅/餐厅","sfjx":false,"sftz":true,"tzTags":true,"url":"cloud://wanyi-3-wanyi-3gkybgsvd882fb24-1319293858/1696919142576-450648328.png","_openid":"one555SeKH4gTdMZQ"}],
[{"_id":"8de6ebcc6524ee680639cddf65bd85c0","sfjx":false,"sftz":true,"tzTags":true,"url":"cloud://wanyi-3wanyi-3gkybgsvd882fb24-1319293858/1696919142577-760341536.png","_openid":"one555SeKH4gUvdMZQ","bh":"ceshitaozhuang","detailUrl":"cloud://wanyi-61-wa82fb24-1319293858/1696919142577-760341536.png","jxfl":"玄关/客厅/餐厅"}]]}],"errMsg":"collection.aggregate:ok"}
- 云函数
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境
// 云函数入口函数
exports.main = async (event, context) => {
// const wxContext = cloud.getWXContext()
let $ = cloud.database().command.aggregate;
let db = cloud.database();
// pictureset、pictureSetRelationShip、picture三表关联
return db.collection('pictureSetRelationShip').aggregate()
.lookup({
from: 'pictureSet',
localField: 'setId',
foreignField: '_id',
as: 'relationList',
})
.replaceRoot({
//replaceRoot指定⼀个已有字段作为输出的根节点,也可以指定⼀个计算出的新字段作为根节点。
//newRoot 代表新的根节点,//$.mergeObjects([]) 可以合并多个元素
newRoot: $.mergeObjects([$.arrayElemAt(['$relationList', 0]), '$$ROOT'])
// arrayElemAt
//就是取relationList数组的第⼀个元素,与原始的根融合在⼀起
})
. project({
//project把指定的字段传递给下⼀个流⽔线,指定的字段可以是某个已经存在的字段,也可以是计算出来的新字段
relationList: 0
})
.match({
jxfl: event.searchtype
})
.lookup({
from: 'picture',
localField: 'pictureID',
foreignField: '_id',
as: 'tzitemPictureList',
})
.group({
// 按照setName分组,将tzitemPictureList拼接到一起,形成新的数组
_id: '$setName',
bh: $.first('$bh'),
tzitemPictureList: $.addToSet('$tzitemPictureList')
})
.end({
success:function(res){
return res;
},
fail(error) {
return error;
}
})
}