我在Firestore中有一个名为Categories的集合。每个类别都有一个手动添加的索引。当我使用GridView循环浏览类别以在UI上显示它们时,类别的顺序是根据它们最初在Firestore中创建的方式选择的。
这里是我目前的代码:
数据库.dart
Future<List<CategoriesModel>> getCategoriesList({String partnerStoreId}) async {
List<CategoriesModel> categories = List();
List<ProductsModel> products = List();
QuerySnapshot snapshot;
// Products
snapshot = await productsCollection
.where('partnerInfo.storeId', isEqualTo: '$partnerStoreId')
.getDocuments();
products = snapshot.documents.map((doc) => ProductsModel.fromSnapshot(doc)).toList();
// Categories
snapshot = await categoriesCollection.getDocuments();
categories =
snapshot.documents.map((doc) => CategoriesModel.fromSnapshot(doc)).toList();
int ind = 0;
categories.forEach((category) {
products.forEach((product) {
if(product.category == category.enId) {
category.productCount = category.productCount + 1;
}
});
categories[ind] = category;
ind++;
});
return categories;
}
在Firestore中,每个类别都有一个名为ux
的键,并且在一个称为index
的子键中手动添加了一个数字
问题:当我在UI中显示类别时,我需要首先显示ux.index = 11
,然后显示ux.index = 3
,然后显示其他所有内容
我正在尝试更改此行:
snapshot = await categoriesCollection.getDocuments();
我正在尝试使用.hwhere、startAt、orderBy等…来查询Firestore
下面是我尝试过的一些例子:
// Here only number 11 is displayed
snapshot = await categoriesCollection.where('ux.index', isEqualTo: 11).getDocuments();
// Here nothing is displayed
snapshot = await categoriesCollection.where('ux.index', isEqualTo: 11).where('ux.index', isEqualTo: 3).getDocuments();
// Nothing is displayed, and even if I use only isLessThanOrEqualTo, the number 11 item is still NOT the first
snapshot = await categoriesCollection.where('ux.index', isLessThanOrEqualTo: 11).where('ux.index', isGreaterThan: 11).getDocuments();
有人能帮忙吗?现在我都快疯了
提前感谢
Joe
让我解释一下为什么最后两个查询都没有返回。
使用多个where
意味着and
,它允许您一次传递多个查询。从字面上看,它就像query1 and query2 and ...
请参阅下面的解释。
// Here nothing is displayed
snapshot = await categoriesCollection.where('ux.index', isEqualTo: 11).where('ux.index', isEqualTo: 3).getDocuments();
因为,您要求ux.index == 11
和ux.index == 3
这自然不会得到任何回报。
这里是
snapshot = await categoriesCollection.where('ux.index', isLessThanOrEqualTo: 11).where('ux.index', isGreaterThan: 11).getDocuments();
因为,您要求ux.index <= 11
和ux.index >= 11
这自然不会返回任何结果,因为条件不适用。
满足您需求的潜在解决方案:
首先,请将snapshot = await categoriesCollection.getDocuments();
替换为snapshot = await categoriesCollection.where('ux.index', descending: false).getDocuments();
假设CCD_ 14从0开始并且递增直到大于11。
此后,请将return categories;
替换为以下代码段。
List orderedCategories = List();
// cherry-pick 11 and 3
orderedCategories.add(categories[11]);
categories.removeAt(11);
orderedCategories.add(categories[3]);
categories.removeAt(3);
// add all the rest
orderedCategories.addAll(categories);
return orderedCategories;
nb!这是一个可以优化的快速解决方案。