讓我說我在“教師”集合中有“教師”集合我在 Firebase 中有“學生”集合,我需要在串列中顯示每個教師的每個學生。我知道我可以創建單獨的學生集合鏈接教師 ID,但這是我需要使用的場景。請幫助我如何讓每個學生都使用 FirebaseFirestore 查詢。
uj5u.com熱心網友回復:
您要查找的內容稱為集合組查詢,它允許您從具有特定名稱的所有集合中讀取/查詢檔案。
根據檔案:
db
.collectionGroup("student")
.get()
.then(
(res) => print("Successfully completed"),
one rror: (e) => print("Error completing: $e"),
);
uj5u.com熱心網友回復:
為此,您將查詢所有教師,然后查詢每個教師內的所有學生。我已經實施了,所以我與您分享我的經驗。首先制作兩個帶有 json 序列化的模型 TeacherModel 和 StudentModel 以方便您。我創建了虛擬模型,您可以在模型中添加欄位。
class TeacherModel {
TeacherModel({
this.students,
});
factory TeacherModel.fromJson(Map<String, dynamic> json) {
/// implement from json
return TeacherModel(students: []);
}
/// all the properties of teacher
List<StudentModel>? students;
Map<String, dynamic> toJson() => {};
}
class StudentModel {
StudentModel();
/// all the properties of student
factory StudentModel.fromJson(Map<String, dynamic> json) {
return StudentModel();
}
Map<String, dynamic> toJson() => {};
}
創建模型后,您有兩個選擇。
1-獲取流中的所有資料,如下所示。
static Stream<List<TeacherModel>> getStreamData() async* {
final firestore = FirebaseFirestore.instance;
var allTeachers = <TeacherModel>[];
final result = firestore.collection('teachers').snapshots();
await for (final r in result) {
final teacherDocs = r.docs;
for (final teacherDoc in teacherDocs) {
final students = (await firestore
.collection('teachers/${teacherDoc.id}/students')
.get())
.docs
.map((e) => StudentModel.fromJson(e.data()))
.toList();
final teacher = TeacherModel.fromJson(teacherDoc.data());
teacher.students = students;
allTeachers.add(teacher);
yield allTeachers;
}
}
}
2-獲取未來的所有資料,如下所示。
static Future<List<TeacherModel>> getFutureData() async {
final firestore = FirebaseFirestore.instance;
var allTeachers = <TeacherModel>[];
final result = (await firestore.collection('teachers').get()).docs;
for (final r in result) {
final students =
(await firestore.collection('teachers/${r.id}/students').get())
.docs
.map((e) => StudentModel.fromJson(e.data()))
.toList();
final teacher = TeacherModel.fromJson(r.data());
teacher.students = students;
allTeachers.add(teacher);
}
return allTeachers;
}
uj5u.com熱心網友回復:
我正在研究一個解決方案,你必須像@Sparko 推薦那樣有創意。在Firestore 檔案中,他們這樣說:
“Cloud Firestore 服務器客戶端庫的 listCollections() 方法列出了檔案參考的所有子集合。
使用移動/Web 客戶端庫無法檢索集合串列。您應該只在受信任的服務器環境中將集合名稱作為管理任務的一部分進行查找。如果您發現在移動/Web 客戶端庫中需要此功能,請考慮重構您的資料,以便子集合名稱是可預測的。”
這也是一種可能的解決方法
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/530401.html
標籤:Google Cloud Collective 扑火力基地镖
上一篇:從2個子矩陣的矩陣中選擇
下一篇:在顫動中顯示json小部件
