firebase - Flutter Firestore 查询 2 个集合

标签 firebase flutter dart google-cloud-firestore

问题已更新

我将如何查询 2 个集合?我有一个愿望 list 集合,其中每个愿望 list 文档如下所示:

documentID: "some-wishlist-id",
modified: "1564061309920",
productId: "2tqXaLUDy1IjxLafIu9O",
userId: "0uM7Dt286JYK6q8iLFyF4tG9cK53"

以及一个产品集合,其中每个产品文档看起来像这样。愿望 list 集合中的 productId 将是产品集合中的文档 ID:
documentID: "2tqXaLUDy1IjxLafIu9O",
dateCreated: "1563820643577",
description: "This is a description for Product 9",
images: ["some_image.jpg"],
isNegotiable: true,
isSold: false,
rentPrice: 200,
sellPrice: 410,
title: "Product 9",
totalWishLists: 0,
userId: "0uM7Dt286JYK6q8iLFyF4tG9cK53"

注意:要清楚的是,wishlist 查询应该返回我需要迭代以检索产品的文档列表。

不确定在这种情况下我是否需要使用流或 future ,但这是我目前所拥有的:
Future<Product> getProduct(String documentId) {
return Firestore.instance
    .collection(APIPath.products())
    .document(documentId)
    .get()
    .then((DocumentSnapshot ds) => Product.fromMap(ds.data));
}

Query getWishListByUser(userId) {
    return Firestore.instance
        .collection(APIPath.wishlists())
        .where('userId', isEqualTo: userId);
}

Future<List<Product>> getProductsWishList(userId) async {
    List<Product> _products = [];

    await getWishListByUser(userId)
        .snapshots()
        .forEach((QuerySnapshot snapshot) {
      snapshot.documents.forEach((DocumentSnapshot snapshot) async {
        Map<String, dynamic> map = Map.from(snapshot.data);
        map.addAll({
          'documentID': snapshot.documentID,
        });

        WishList wishList = WishList.fromMap(map);

        await getProduct(wishList.productId).then((Product product) {
          print(product.title); // This is printing
          _products.add(product);
        });
      });
    });

    // This is not printing
    print(_products);

    return _products;
  }

谢谢

最佳答案

对于任何数据库,您通常需要连接来自多个表的数据来构建 View 。

在关系数据库中,您可以通过使用 JOIN 子句,使用一条语句从这些多个表中获取数据。

但是在 Firebase(和许多其他 NoSQL 数据库)中,没有内置的方法来连接来自多个位置的数据。所以你必须在你的代码中做到这一点。

创建愿望 list 模型:

class Wishlist {

  Wishlist({
    this.id,
    this.modified,
    this.productId,
    this.userId
  });

  final String id;
  final String modified;
  final String productId;
  final String userId;

  Wishlist.fromMap(json)
    : id = json['id'].toString(),
      modified = json['modified'].toString(),
      productId = json['productId'].toString(),
      userId = json['userId'].toString();
}

在您的 API 文件中,执行以下操作:
final Firestore _fireStore = Firestore.instance;    

getWishList(wishlistId) async {
  return await _fireStore.collection('wishlists').document(wishlistId).get();
}

getProduct(productId) async {
  return await _fireStore.collection('product').document(productId).get();
}

Future<List<Product>>getProductsWishList(wishlistId) async {

  var _wishlists = null;
  List<Product> _products = []; // I am assuming that you have product model like above

  await getWishList(wishlistId).then((val) {
    _wishlists = Wishlist.fromMap(val.data);

    _wishlists.forEach((wish) {
      await getProduct(wish.productId).then((product) {
          _products.add(product));
      });
    });
  });

  return _products;
}

关于firebase - Flutter Firestore 查询 2 个集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57204174/

相关文章:

java - 当无法使用 Android 将数据写入 Firebase 数据库时如何获取错误消息

swift - 在 Firebase 中保存用户名 - Swift

generics - 尝试在父类的Dart中捕获错误

flutter - 从 Future 任一方法中调用两个方法,均具有 Future 任一返回类型

flutter - 为什么我应该避免在 getter 和 setter 中包装字段?

ios - 如何在 Swift 中写入 Firebase ref 的最后一个 child ?

android - RecyclerView 不会显示任何数据

ios - 在Flutter中安装 native iOS Pod

dart - Flutter 默认字体大小

android - Flutter Firestore使用setDate批量写入并合并