【问题标题】:Flutter Firestore query 2 collectionsFlutter Firestore 查询 2 个集合
【发布时间】:2019-12-03 20:41:35
【问题描述】:

问题已更新

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

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

还有一个产品集合,其中每个产品文档看起来像这样。愿望清单集合中的 productId 将是产品集合中的 documentID:

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"

注意:为了清楚起见,愿望清单查询应返回我需要迭代以检索产品的文档列表。

不确定在这种情况下我是否需要使用流或期货,但这是我目前所拥有的:

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;
  }

谢谢

【问题讨论】:

  • 您想在列表中呈现该数据吗?是指产品中的一些字段和愿望清单中的一些字段?
  • @MuhammadNoman 我只想退回愿望清单中的产品。所以愿望清单中没有任何内容。
  • 你有那个愿望清单的wishlistId?
  • 是的。我会将 documentID 添加到原始问题中。
  • 查看以下答案

标签: firebase flutter dart google-cloud-firestore


【解决方案1】:

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

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

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

创建愿望清单模型:

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;
}

【讨论】:

  • 感谢您,愿望清单查询将返回愿望清单文档列表,而不是单个愿望清单文档
  • wishlist查询如何返回wishlist文档列表?您正在使用 id(主键)查询愿望清单表,应该返回一个文档。
  • 跨多个文档运行会不会延迟太多?
  • 会的,但您别无选择。因为它是 NoSQL 数据库
【解决方案2】:

我上周末找到了解决方案,但忘记发布了。想我现在这样做,以防其他人有这个问题。

我使用了StreamBuilderFutureBuilder 的组合。不确定是否有更好的答案,也许结合多个流?但这对我有用。

return StreamBuilder<List<Wishlist>>(
  stream: wishListStream(userId),
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      List<Wishlist> wishlists = snapshot.data;

      if (wishlists.length > 0) {
        return new GridView.builder(
          scrollDirection: Axis.vertical,
          itemCount: wishlists.length,
          itemBuilder: (context, index) {
            Future<Product> product =
                getProduct(wishlists[index].productId);

            return FutureBuilder(
              future: product,
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  Product product = snapshot.data;

                  // Do something with product
                } else {
                  return Container();
                }
              },
            );
          },
          gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
          ),
        );
      } else {
        return Text('No products in your wishlist');
      }
    }

    if (snapshot.hasError) {
      print('WishlistPage - ${snapshot.error}');
      return Center(child: Text('Some error occurred'));
    }

    return Center(child: CircularProgressIndicator());
  },
);

【讨论】:

    猜你喜欢
    • 2020-01-27
    • 2021-04-08
    • 2020-02-04
    • 2020-10-10
    • 2018-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多