Cloud Firestore get collection by reference from another collection

十年热恋 提交于 2020-05-17 06:06:42

问题


I have a collection called Products and another one named Category.

Products document has a field idCategory, referencing category's id.

I want to get all documents from Products where the category name is equals "Soda".

How can I do that?


回答1:


I want to get all documents from Products where the category name is equals "Soda".

Because you don't have all data in a single document, you need to query your database twice. Once to get the id of the category which is "Soda" in this case and then based on that id get the corresponding products. This is because Firestore doesn't support queries across multiple collections. A single query may only use properties of documents in a single collection.

By why to query the database twice, which is aslo costly when you can query once and get the desired documents. For that, you need to make a little change in your database schema. Since a single product may belong to multiple categories, your new schema should look like this:

Firestore-root
    |
    --- products (collection)
          |
          --- productId (document)
                |
                --- productName: "Soda Water"
                |
                --- category: ["Soda", "Other Category"]
                |
                --- //Other properties

To get all document that are apart of Soda category, please use the following lines of code:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference productsRef = rootRef.collection("products");
Query query = productsRef.whereArrayContains("category", "Soda");

Edit: You can also hold references instead of only ids but for that, please see my answer from this post.




回答2:


It looks like you would do a simple query (Firebase Docs Reference):

FirebaseFirestore db = FirebaseFirestore.getInstance();

CollectionReference productsRef = db.collection("Products");

Query query = productsRef.whereEqualTo("idCategory", "Soda");

query.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
    @Override
    public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
        /// do things with response
    }
})
.addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception e) {
        /// do things with error
    });


来源:https://stackoverflow.com/questions/53889433/cloud-firestore-get-collection-by-reference-from-another-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!