首页 > 解决方案 > 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方法,当我引用它时跳过shopProductShop 。

这是唯一/最好的方法吗?

谢谢

标签: firebaseflutterdartgoogle-cloud-firestore

解决方案


据我所知,您有两种选择

  • 第一个是添加文档引用而不是引用类

    像这样的东西

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模型做同样的事情。

厘米如果您需要更多详细信息


推荐阅读