You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何基于Firebase父分类获取旗下所有商品?

问题描述

我在Firebase中有两个集合:

CategoriesCollection

[
  {"Id":"1","Title":"Electronics","ParentId":""},
  {"Id":"2","Title":"Clothe","ParentId":""},
  {"Id":"3","Title":"Mobile","ParentId":"1"},
  {"Id":"4","Title":"Laptop","ParentId":"1"},
  {"Id":"5","Title":"Shirts","ParentId":"2"},
  {"Id":"6","Title":"Jeans","ParentId":"2"}
]

其中ParentId为空字符串表示该分类是父分类,非空则为对应父分类的子分类(例如Mobile是ID为1的Electronics的子分类)。

ProductsCollection

[
  {"id":"1", "title":"S23 Ultra","CategoryId":"3"},
  {"id":"2", "title":"S24 Ultra","CategoryId":"3"},
  {"id":"3", "title":"Macbook Air","CategoryId":"4"},
  {"id":"4", "title":"Spykar shirt","CategoryId":"5"}
]

原本我通过以下代码根据子分类ID获取对应商品:

Future<List<ProductModel>> categoryProducts(String categoryId) async {
  try {
    print(categoryId.toString());
    final list=await FirebaseFirestore.instance.collection('Products').where('CategoryId',isEqualTo: categoryId).get();
    return list.docs.map((e) => ProductModel.fromSnapshot(e)).toList();
  } catch (e) {
    throw e;
  }
}

现在需要改为只显示Electronics和Clothe两个父分类按钮,点击Electronics时需获取其下所有子分类(Mobile、Laptop)的商品,请问如何编写对应的Firebase查询代码?

解决方案

要实现点击父分类获取其下所有子分类的商品,需要分两步操作:

  • 先查询该父分类下的所有子分类ID
  • 根据子分类ID列表批量查询对应的商品

以下是完整的实现代码:

// 获取指定父分类下的所有子分类ID
Future<List<String>> getChildCategoryIds(String parentCategoryId) async {
  try {
    final snapshot = await FirebaseFirestore.instance
        .collection('Categories')
        .where('ParentId', isEqualTo: parentCategoryId)
        .get();
    
    return snapshot.docs.map((doc) => doc['Id'] as String).toList();
  } catch (e) {
    throw e;
  }
}

// 根据父分类ID获取其下所有子分类的商品
Future<List<ProductModel>> getParentCategoryProducts(String parentCategoryId) async {
  try {
    // 获取子分类ID列表
    final childCategoryIds = await getChildCategoryIds(parentCategoryId);
    
    if (childCategoryIds.isEmpty) {
      return [];
    }
    
    // 批量查询所有子分类对应的商品
    final productsSnapshot = await FirebaseFirestore.instance
        .collection('Products')
        .where('CategoryId', whereIn: childCategoryIds)
        .get();
    
    return productsSnapshot.docs.map((e) => ProductModel.fromSnapshot(e)).toList();
  } catch (e) {
    throw e;
  }
}

代码说明

  • getChildCategoryIds函数:查询Categories集合中ParentId匹配目标父分类ID的文档,提取所有子分类的Id字段组成列表。
  • getParentCategoryProducts函数:先调用上述函数获取子分类ID列表,再使用whereIn条件查询Products集合中CategoryId属于该列表的所有商品。
  • 注意:Firebase的whereIn条件最多支持10个元素,如果你的子分类数量超过10个,需要拆分多次查询后合并结果。

内容的提问来源于stack exchange,提问作者user22362195

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 02:17:50