【发布时间】:2021-05-23 07:11:49
【问题描述】:
我正在构建一个与库存管理系统非常相似的应用。我现在的障碍是 Firestore 中允许的查询数量,因为它不允许多个 .where()。
所以使用库存管理系统的概念,我们创建了一个集合:
我们将其命名为 'InventoryCollection'。假设它有 3 个字段:
- ItemID
- ItemName
- DateAdded
'InventoryCollection' 中的每个文档都有一个名为 'PurchaseHistory' 的子集合: 它有字段:
- PurchaseID (auto generated document id)
- ItemID (from parent collection document)
- PurchaseDate
- Quantity
困境:如何使用先进先出的概念来扣除物品的数量? 因此,假设 Item1 有 4 PurchseHistory 数据。假设其中一个的数量为 0,因为它们已经售出。
- PurchaseID: 12340
- ItemID: 00001
- PurchaseDate: 01-feb-2021
- Quantity: 0
- PurchaseID: 12341(auto generated document id)
- ItemID: 00001
- PurchaseDate: 02-feb-2021
- Quantity: 10
- PurchaseID: 12342
- ItemID: 00001
- PurchaseDate: 03-feb-2021
- Quantity: 5
- PurchaseID: 12343
- ItemID: 00001
- PurchaseDate: 03-feb-2021
- Quantity: 15
我需要找到一种方法来检索 PurchaseId 12341 以使用以下参数获取“First In”。然后我可以自己想办法“先出”:
- 获取所有 ItemID 为 00001 的 PurchaseHistory 文档
- 仅获取具有 1 个或多个 Quantity 的文档
- 按 PurchaseDate 对数据进行排序,以便第一个结果将是 2 月 2 日的条目
- 将查询结果限制为 1 只获取 2 月 2 日的文档
- 获取要在以下方法中使用的该文档的 purchaseID:
void _deductQuantity(String itemId, String PurchaseID {
final itemCollection = FirebaseFirestore.instance.collection('InventoryCollection').doc(ItemId).collection('PurchaseHistory').doc(purchaseID);
itemCollection.update({
'Quantity': _quantity - int.parse(_editItemQuantityController.text.trim()),
});
}
在我看来,查询是这样的:
String purchaseIdStream;
final docRef = FirebaseFirestore.instance.collection('InventoryCollection').doc(ItemId).collection('PurchaseHistory').doc();
purchaseIdStream = await docRef
.where('ItemId', isEqualTo: ItemId)
.where('Quantity', isGreaterThan: 0)
.orderBy('PurchaseDate')
.get();
var _id = purchaseIdStream.ref.documentID;
我完全理解 Firebase 不允许 orderby,如果您在 .where 中没有该字段用于购买。所以绝对不可能在上面的代码上做到这一点。因为我已经有 2 个 where 和第 3 个 where 是不可能的。
我知道我必须进行服务器端过滤而不是多个 .where 但是,我只是前端开发人员。我对后端概念的理解非常有限。所以我需要关于如何在 dart/flutter 中实现这一点的糟糕指导。
我们将不胜感激任何建议。谢谢!
【问题讨论】:
-
我相信您可以使用 CollectionGroup 查询 firebase.googleblog.com/2019/06/…
标签: firebase flutter dart google-cloud-firestore