firebase - Firestore 中的两个对象相互引用
问题描述
我有 2 个对象存储在 Firestore Product & Shop 未来可能会有很多 Product 和 Shop,所以我在 Product 中有 Shop DocumentReference,反之亦然
这是他们的样子
class Shop extends Equatable {
final String? id;
final String name;
final List<Product?> shopProduct;
final DateTime createDate;
...
static Future<Shop> fromDocument(DocumentSnapshot doc) async {
final data = doc.data() as Map<String, dynamic>;
final shopProductRef = data['shopProduct'];
final List<Product?> shopProductList;
if (shopProductRef.isNotEmpty) {
shopProductList = List.from(shopProductRef.map((ref) async {
Product.fromDocument(await ref!.get());
}));
} else {
shopProductList = [];
}
return Shop(
id: doc.id,
name: data['name'],
shopProduct: shopProductList,
createDate: (data['createDate'] as Timestamp).toDate(),
);
}
和
class Product extends Equatable {
final String? id;
final Shop shop;
final double price;
final String title;
final DateTime date;
...
static Future<Product?> fromDocument(DocumentSnapshot doc) async {
final data = doc.data() as Map<String, dynamic>;
final shopRef = data['shop'] as DocumentReference;
final shopDoc = await shopRef.get();
return Product(
id: doc.id,
shop: await Shop.fromDocument(shopDoc),
price: data['price'],
title: data['title'],
date: (data['date'] as Timestamp).toDate(),
);
}
这是我认为首先应该起作用的方法,但它带来了一个问题,即它会导致循环,因为两者都相互引用。
我提出了一个修复程序,它创建了第二个fromDocument方法,当我引用它时跳过shopProduct或Shop 。
这是唯一/最好的方法吗?
谢谢
解决方案
据我所知,您有两种选择
第一个是添加文档引用而不是引用类
像这样的东西
class Product extends Equatable {
final String? id;
final DocumentRefrence<Shop> shop;
final double price;
final String title;
final DateTime date;
...
并对Shop
模型做同样的事情
class Shop extends Equatable {
final String? id;
final String name;
final List<DocumentReference<Product>?> shopProduct;
final DateTime createDate;
...
- 第二个就像你提到的,为
Product
模型创建一个方法并命名它,例如:Map<String, dynamic> toShopCollection()
并在firestore中设置商店时使用它,并对Shop
模型做同样的事情。
厘米如果您需要更多详细信息
推荐阅读
- linux - 如何将命令的输出作为对 bash shell 中变量的引用
- flutter - “错误:在 Flutter 中执行数字求和时,不能将类型为‘double’的值分配给‘int’类型的变量”
- python - Python:使用rolling + apply和一个需要2列作为pandas参数的函数
- react-native - React Native 网络信息
- selenium - 如何通过用于 Zalenium 消息的 selenium-side-runner 将 cookie 添加到在网格中运行的 Selenium IDE 测试
- javascript - Jest 的 Async/Await 测试在 Node js 中不起作用
- java - java Calendar.toInstant() 和 Instant.atZone 中的不准确/随机性(也是 Local/ZonedDateTime.ofInstant())
- python - Python Flask 日期转换
- node.js - 如果用户没有登录,不要试图让用户做出反应
- javascript - 连接不是从网页开始的