英文:
Flutter Cloud Firestore ODM, how to convert DocumentReference<Model> to DocumentReference<Map<String, dynamic>>
问题
To convert a VendorDocumentReference
to a DocumentReference<Map<String, dynamic>>
, you can use the DocumentReference
constructor. Here's how you can achieve this conversion:
// Assuming you have a VendorDocumentReference named vendorDocRef
DocumentReference<Map<String, dynamic>> convertedRef = DocumentReference<Map<String, dynamic>>(
vendorDocRef.firestore,
vendorDocRef.path,
);
// Now, convertedRef is a DocumentReference<Map<String, dynamic>> that you can use in your Invoice creation.
This code creates a new DocumentReference
using the Firestore instance and path of your VendorDocumentReference
, which effectively converts it into the desired type.
英文:
If I have two collections in Firebase:
Invoices:
invoice1 {
Vendor: (reference) /Vendors/vendor1
}
Vendors:
vendor1 {
Name: "John Doe"
}
and if I model them with cloud firestore odm generator as:
@Collection<Invoice>('Invoices')
@firestoreSerializable
class Invoice {
Invoice({
required this.id,
required this.vendor,
});
@Id()
String id;
@JsonKey(name: 'Vendor')
DocumentReference<Map<String, dynamic>> vendor;
}
final invoicesRef = InvoiceCollectionReference();
@Collection<Vendor>('Vendors')
@firestoreSerializable
class Vendor {
Vendor({
required this.id,
required this.name,
});
@Id()
String id;
@JsonKey(name: 'Name')
String name;
}
final vendorsRef = VendorCollectionReference();
when I select a vendor from vendorsRef, I obtain a VendorDocumentReference. In order to create a new invoice with this vendor, I need to convert it to DocumentReference<Map<String, dynamic>>. How do I achieve this conversion?
VendorDocumentReference or DocumentReference<Vendor> don't seem to have a way to perform this conversion.
答案1
得分: 0
不要紧。我已经用转换器解决了:
class VendorConverter extends JsonConverter<DocumentReference<Vendor>,
DocumentReference<Map<String, dynamic>>> {
@
<details>
<summary>英文:</summary>
Nevermind. I've solved with converter:
class VendorConverter extends JsonConverter<DocumentReference<Vendor>,
DocumentReference<Map<String, dynamic>>> {
@override
DocumentReference<Vendor> fromJson(
DocumentReference<Map<String, dynamic>> json) {
return vendorsRef.doc(json.id).reference;
}
@override
DocumentReference<Map<String, dynamic>> toJson(
DocumentReference<Vendor> object) {
final path = vendorsRef.doc(object.id).path;
return FirebaseFirestore.instance.doc(path);
}
const VendorConverter();
}
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论