I'm recently started using Firebase firestore. I'm stuck at the point were the collection have sub collections and get those items to my model.
Let say I have this collection
meats
id : 1
name : Chicken
subMeats
id : 11
name : Country Chicken
id : 12
name : Broiler Chicken
meats
id : 2
name : Pork
subMeats
id : 21
name : White Pork
id : 22
name : Black Pork
return meatTypeCollection.get().then((value) {
value.docs.forEach((mainDoc) {
// MainMeatEntity.fromSnapshot(mainDoc)
_logger.i(mainDoc.data()['name']);
meatTypeCollection
.doc(mainDoc.id)
.collection('subMeats')
.get()
.then((snapShots) {
snapShots.docs.forEach((doc) {
_logger.i(doc.data()['name']);
MainMeat.fromEntity(MainMeatEntity.fromSnapshot(doc));
});
});
});
//return MeatTypes.fromEntity(MeatTypeEntity.fromJson(value.docs));
}).catchError((error) => _logger.e("Failed to load meat types : $error"));
The above does not capture the collection. I use entity to model.
import 'package:flutter/cupertino.dart';
import 'entities/main_meat_entity.dart';
import 'entities/meat_type_entity.dart';
@immutable
class MainMeat {
final String id;
final String name;
final MeatTypeEntity subMeats;
final String shopId;
const MainMeat({
this.id,
this.name,
this.subMeats,
this.shopId,
});
static MainMeat fromEntity(MainMeatEntity mainMeatEntity) {
return MainMeat(
id: mainMeatEntity.id,
name: mainMeatEntity.name,
subMeats: mainMeatEntity.subMeats,
shopId: mainMeatEntity.shopId,
);
}
MainMeatEntity toEntity() {
return MainMeatEntity(id, name, subMeats, shopId);
}
static const empty = MainMeat(id: '', shopId: "", name: "");
}
-----------------------------****************--------------------
part 'meat_type_entity.g.dart';
@JsonSerializable()
class MeatTypeEntity extends Equatable {
final String id;
final String name;
final String shopId;
const MeatTypeEntity(this.id, this.name, this.shopId);
factory MeatTypeEntity.fromJson(Map<String, dynamic> json) =>
_$MeatTypeEntityFromJson(json);
Map<String, dynamic> toJson() => _$MeatTypeEntityToJson(this);
@override
List<Object> get props => [
id,
name,
shopId,
];
static MeatTypeEntity fromSnapshot(DocumentSnapshot snap) {
return MeatTypeEntity(
snap.id,
snap.data()['name'],
snap.data()["shopId"],
);
}
Map<String, Object> toDocument() {
return {
"id": id,
'mainMeat': name,
"shopId": shopId,
};
}
}
I can list it's collection and sub collections fine. But not sure to load into my model. Any help appreciated thanks.
question from:
https://stackoverflow.com/questions/65661995/adding-collection-and-subcollection-data-to-model-entity-from-firestore-firebase 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…