I have data something like Customer -> documnetid -> Orders(collection) same as for all customer. I need to show the list of orders from all the customer in a list. If a customer orders a item again it needs to create another list.
FirebaseFirestore.instance
.collection("customer")
.doc('a44d4c1b-7faa-4139-b707-a40499fe4ce5')
.collection("orders")
.where('orderStatus', isEqualTo: 'ordered')
.snapshots(),
I can get the data if I provide specific document id. But I need to get orders from all the customers. Please help me in this. Thank you
CodePudding user response:
You need to change your data structure. Like you can create a new different separate collection for orders with the same fields customer id field.
so you can get all orders and orders by customer id
So if you want to get an orders for a particular customer you can get by this :
FirebaseFirestore.instance
.collection("orders")
.where('customerId', isEqualTo: 'a44d4c1b-7faa-4139-b707-a40499fe4ce5')
.snapshots(),
And you can get all orders like this:
FirebaseFirestore.instance
.collection("orders")
.snapshots(),
OR if you still want to do it by your data structure you can do it by loop
List orders = [];
FirebaseFirestore.instance
.collection('customer')
.get().then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((doc) {
dynamic data = doc.data();
orders.addAll(data['orders'] as List);
});
});
CodePudding user response:
You should use a Collection Group query, as explained in the Firebase documentation and in the Dart cloud_firestore
package documentation.
Something along these lines:
FirebaseFirestore.instance
.collectionGroup("orders")
.where('orderStatus', isEqualTo: 'ordered')
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((doc) {
//...
});
});