LuckyDaniel
LuckyDaniel
  • 发布:2025-12-10 13:31
  • 更新:2025-12-10 13:32
  • 阅读:21

怎么用字段是数组为空作为条件,来做数据库的查询?

分类:uni-app

用的这段代码:
await companyTable
.where("staff_id.length > 0")
.field("name, staff_id")
.get()
.then(res => {
console.log("公司名称数组", res.result);
for (let i = 0; i < res.result.data.length; i++) {
that.companies.push(res.result.data[i].name);
}
})
条件语句是:"staff_id.length > 0", staff_id是数组类型,我数据表里有staff_id不为空的数据,但就是查不出来,这是怎么回事?要以数组为空作为条件,应该怎么写?

2025-12-10 13:31 负责人:无 分享
已邀请:
Ask小助手

Ask小助手 - Ask社区AI助手

在 uni-app 的 uniCloud 数据库查询中,要查询数组字段不为空的记录,正确的 JQL 语法不是直接用 .length 属性。

问题原因:

  1. uniCloud 的 JQL 查询语法不支持直接在 where 条件中使用 JavaScript 的 .length 属性
  2. 正确做法是使用 $size 操作符或检查数组是否不等于空数组

解决方案:

// 方法1:使用 $size 操作符(推荐)  
await companyTable  
  .where('staff_id != null && staff_id.$size > 0')  
  .field('name, staff_id')  
  .get()  

// 方法2:检查是否不等于空数组  
await companyTable  
  .where('staff_id != []')  
  .field('name, staff_id')  
  .get()

注意事项:

  • 确保 staff_id 字段确实是数组类型,不是字符串
  • 如果有些文档没有 staff_id 字段,需要加上 staff_id != null 条件
  • 可以先不加 where 条件查询所有数据,在客户端过滤验证数据是否存在:
    // 调试用:先获取所有数据检查  
    await companyTable.field('name, staff_id').get().then(res => {  
    console.log('原始数据:', res.result.data);  
    console.log('非空staff_id数据:', res.result.data.filter(item => item.staff_id && item.staff_id.length > 0));  
    });  

详细参考:uniCloud JQL 文档 - 数组查询

内容为 AI 生成,仅供参考

要回复问题请先登录注册