简体   繁体   中英

Flutter Firestore search from more than 1 collection

So what I'm trying to do is search from 2 or more collection. Here's my collection:

Tier-1
Tier-2
Tier-3

Let's say I want to search with key "name" and what I want to achieve is, it will searching from Tier-1 to Tier-3. If there's no document equal to "name" from Tier-1, it will continue to Tier-2, if there's document equal to "name" at Tier-2, it will stop and return the document. Is it possible to achieve? or my logic is totally wrong

Basically what you are saying, is that you have the following structure:

Tier-1 (collection) -> docId(document) -> Tier-2 (collection) -> docId(document) -> Tier-3 (collection) -> docId(document)

You can do the following:

  void getData() {
    Firestore.instance
        .collection("Tier-1")
        .where("name", isEqualTo: "peter")
        .getDocuments()
        .then((querySnapshot) {
      querySnapshot.documents.forEach((result) {
        if (result.exists) {
          print(result.data);
        } else {
          Firestore.instance
              .collectionGroup("Tier-2")
              .where("name", isEqualTo: "peter")
              .getDocuments()
              .then((querySnapshot) {
            querySnapshot.documents.forEach((result) {
              if (result.exists) {
                print(result.data);
              } else {
                Firestore.instance
                    .collectionGroup("Tier-3")
                    .where("name", isEqualTo: "peter")
                    .getDocuments()
                    .then((querySnapshot) {
                  querySnapshot.documents.forEach((result) {
                    if (result.exists) {
                      print(result.data);
                    } else {}
                  });
                });
              }
            });
          });
        }
      });
    });
  }

First you check the top collection Tier-1 , if it returns no result, then you need to check the subcollection Tier-2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM