【问题标题】:Firestore Query Document's SubcollectionFirestore 查询文档的子集合
【发布时间】:2020-07-26 12:17:19
【问题描述】:

我正在学习 Flutter/Dart 并尝试连接到我的 Firestore 数据库。我想查询文档的集合,然后查询该文档中的集合。我还在学习 Dart,但我发现异步流构建应该是最好的方法。

我试过db.instance.collect('').document('').collection('').snapshot(),但streambuilder似乎不支持这个,我得到了错误

没有为类型“查询”定义方法“集合”。

我必须在db.instance.collection('').where('name' isEqualto: 'Name').snapshots()之后结束我的查询

下面是一个例子。

我的目标是查询所有类并将它们显示在一个列表中。

示例 -
教师   教师姓名 类    Class1    Class2

       import 'package:flutter/material.dart';
       import 'package:cloud_firestore/cloud_firestore.dart';
       
       class ClassListPage extends StatelessWidget{
         @override
       
       
         Widget build(BuildContext context){
           return Material(
                 child: new StreamBuilder<QuerySnapshot>(
               stream: Firestore.instance.collection('Teachers').
               where('name', isEqualTo: 'Dr. Who')
              //.collection('Classes') <--This is not working
               .snapshots(),
               //HERE is where I want to query for the 'classes' collection then query
           //for the documents within
               builder:(BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot){
                 if(!snapshot.hasData)return new Text('..Loading');
                 return new ListView(
                   children: snapshot.data.documents.map((document){
                     return new ListTile( 
                       title: new ListTile(
                         title: new Text(document['name']),
       
                       ),
                     );
                     
                   }).toList(),
                   );
               }
       
             ),
           );
           
         }
       }

【问题讨论】:

    标签: flutter dart google-cloud-firestore nosql


    【解决方案1】:

    在您的问题中,您说您正在使用db.instance.collection('').document('').collection('').snapshot(),但在您的代码中,没有调用document()。这是我看到的:

    Firestore.instance
        .collection('Teachers')
        .where('name', isEqualTo: 'Dr. Who')
        .collection('Classes')
        .snapshots()
    

    这是行不通的,因为where() 返回一个 Query,而 Query 没有 collection() 方法。听起来您需要做的是执行该查询,查看结果集中的文档(可能有任何数字,而不仅仅是 1),然后对每个文档的子集合进行另一个查询。

    【讨论】:

    • 这不是工作代码。问题是我无法查询集合('Classes')。工作查询是 .instance.collection('Teacher').where('name' = 'Dr.Who).snapshot()。由于某种原因,我不能包含第二个集合查询。我仍在学习如何拍摄我得到的快照并从那里再次查询。这就是我卡住的地方。
    • 对,我的回答是,您需要执行该工作查询,迭代结果中的文档,并针对第一个查询中的文档子集合执行另一个查询。
    猜你喜欢
    • 2021-04-08
    • 1970-01-01
    • 2021-07-12
    • 2018-06-19
    • 1970-01-01
    • 2020-12-02
    • 2021-09-25
    • 2020-05-08
    • 1970-01-01
    相关资源
    最近更新 更多