dart 如何获取文档内部子文档的值的总和?

nwnhqdif  于 2023-05-26  发布在  其他
关注(0)|答案(1)|浏览(109)

我想从Firebase中另一个文档的子文档中获取字段值的总数
database tree
我想得到糖浆中所有成分的价格值,这样我就可以把它加到糖浆的总价中
我只见过COUNT函数,但在这种情况下它对我没有帮助。

yyhrrdl8

yyhrrdl81#

要从Firebase中的另一个文档的子文档中获取字段值的总和,可以在代码中组合使用Firestore查询和数据操作。下面是一个使用Flutter和cloud_firestore包实现此功能的示例:

import 'package:cloud_firestore/cloud_firestore.dart';

Future<double> getTotalSyrupPrice() async {
  // Get a reference to the syrup document
  DocumentReference syrupRef = FirebaseFirestore.instance
      .collection('your_collection') // Replace with your collection name
      .doc('syrup_document_id'); // Replace with the ID of the syrup document

  // Get all the ingredients subcollection documents of the syrup
  QuerySnapshot ingredientsSnapshot = await syrupRef
      .collection('ingredients') // Replace with your subcollection name
      .get();

  double totalPrice = 0;

  // Iterate over the ingredient documents and sum up the price values
  for (DocumentSnapshot ingredientDoc in ingredientsSnapshot.docs) {
    Map<String, dynamic>? ingredientData = ingredientDoc.data();
    if (ingredientData != null && ingredientData.containsKey('price')) {
      totalPrice += ingredientData['price'];
    }
  }

  return totalPrice;
}

在上面的示例中,将'your_collection'替换为您的集合的名称,将'syrup_document_id'替换为您想要从中检索成分的糖浆文档的ID。另外,请确保将“配料”替换为存储配料的子集合的名称。
getTotalSyrupPrice函数执行查询以获取糖浆文档的子集合中的所有成分文档。然后,它遍历成分文档并对价格值求和。最后,返回总价。
只要需要检索糖浆成分的总价,就可以调用getTotalSyrupPrice函数。记住处理任何潜在的错误并等待函数,因为它返回Future。

相关问题