uni-app中lookup方法内只允许使用子查询(let+pipeline)方式,非外键字段如何关联查询

uni-app中lookup方法内只允许使用子查询(let+pipeline)方式,非外键字段如何关联查询

操作步骤:

  • 能使用非外键关联

预期结果:

  • 能使用非外键关联

实际结果:

  • 不能

bug描述:

  • lookup方法内只允许使用子查询(let+pipeline)方式,非外键字段如何关联查询
2 回复

那就不能使用jql了,可以在云函数里面用原始写法 https://uniapp.dcloud.net.cn/uniCloud/cf-database-aggregate.html#aggregate-lookup

更多关于uni-app中lookup方法内只允许使用子查询(let+pipeline)方式,非外键字段如何关联查询的实战教程也可以访问 https://www.itying.com/category-93-b0.html


uni-app 中,lookup 方法用于实现多表关联查询,但默认情况下,lookup 方法仅支持通过外键字段进行关联查询。如果你需要通过非外键字段进行关联查询,可以使用 let + pipeline 的方式来实现。

示例场景

假设你有两个集合:usersordersusers 集合中包含 userIduserName 字段,orders 集合中包含 orderIduserName 字段。现在你想通过 userName 字段将 usersorders 进行关联查询。

实现步骤

  1. 使用 let 定义变量:在 lookup 方法中,使用 let 定义变量,将当前集合的字段赋值给变量。

  2. 使用 pipeline 进行子查询:在 pipeline 中,使用 $match 进行条件匹配,实现非外键字段的关联查询。

示例代码

const db = uniCloud.database();

db.collection('users')
  .aggregate()
  .lookup({
    from: 'orders',
    let: {
      userName: '$userName' // 将 users 集合中的 userName 字段赋值给变量 userName
    },
    pipeline: [
      {
        $match: {
          $expr: {
            $eq: ['$userName', '$$userName'] // 使用 $expr 表达式进行条件匹配
          }
        }
      }
    ],
    as: 'userOrders' // 将查询结果赋值给 userOrders 字段
  })
  .end()
  .then(res => {
    console.log(res);
  })
  .catch(err => {
    console.error(err);
  });
回到顶部