在Flutter中创建对象时,可以存储Firestore记录本身的引用吗?

cu6pst1q  于 2023-11-21  发布在  Flutter
关注(0)|答案(1)|浏览(158)

目标是获取对应于此Customer的上游DocumentReference的引用,以便在对引用此文档的另一个集合的查询中使用。
有没有办法在这个类中添加一个私有变量id,它将对应于文档,就好像Firestore路径是customer/id一样?实际上,cid在底部的查询中。

class Customer {
  const Customer({
    required this.isAdmin,
  });

  final bool? isAdmin;

  Customer.fromJson(Map<String, Object?> json)
      : this(
          isRepAdmin: json['is_rep_admin'] as bool?,
        );

  Map<String, Object?> toJson() => {
        'is_admin': isAdmin,
      };
}

Query<Customer> customerQuery(bool criteria) {
  final dataRef = FirebaseFirestore.instance.collection('customer').
    withConverter<Customer>(
      fromFirestore: (s, _) => Customer.fromJson(data),
      toFirestore: (o, _) => o.toJson());
  return dataRef.where('is_admin', isEqualTo: criteria);
}

字符串

nkoocmlb

nkoocmlb1#

你可以从withConverterfromFirestore部分的snapshot中获取文档的引用,在我的例子中,最优雅的方法是扩展fromJson,除了json数据有效载荷之外,还包括引用。

const Customer({
    required this.ref,
    required this.isAdmin,
  });

  final DocumentReference ref;
  final bool? isAdmin;

  Customer.fromJson(DocumentReference ref, Map<String, Object?> json)
      : this(
          ref: ref,
          isRepAdmin: json['is_rep_admin'] as bool?,
        );

  Map<String, Object?> toJson() => {
        // IMPORTANT: do not convert 'id' back otherwise you'd write it to your data store
        'is_admin': isAdmin,
      };
}

Query<Customer> customerQuery(bool criteria) {
  final dataRef = FirebaseFirestore.instance.collection('customer').
    withConverter<Customer>(
      fromFirestore: (s, _) => Customer.fromJson(s.reference, s.data()!}),
      toFirestore: (o, _) => o.toJson());
  return dataRef.where('is_admin', isEqualTo: criteria);
}

字符串
现在您可以使用customer.ref访问文档的自我引用,就像访问customer.isAdmin一样。

相关问题