【问题标题】:Swift Firebase query child of child [duplicate]孩子的Swift Firebase查询孩子[重复]
【发布时间】:2018-01-25 18:55:07
【问题描述】:

所以我在这里被困了半天,我试图获得 Arya 的所有主题,但我很难做到。

这是 Firebase 中的示例结构。

-Subjects
    -math
        id: 1
        name: Math
        -students
            -Arya
                id: 1
                name: Arya
            -JonSnow
                id: 2
                name: JonSnow
            +justsomename
    +science
    +english
    +history
    +computer

然后我找到了这个Querying in Firebase by child of child

我试过了

ref.queryOrdered(byChild: "students/name").queryEqual(toValue: "Arya").observeSingleEvent(of: .value, with: { snapshot in

        print(snapshot)
    })

ref == 主题

但这就是回报

Snap (subjects) <null>

查询是否正确,我只是做错了什么?

【问题讨论】:

  • 你想获得什么价值?
  • 我正在尝试与一个名叫 Arya 的学生一起学习所有科目。
  • @MaappeaL 你试过分开students/name吗?我不知道这是否会解决它,但我会尝试一下:child("students").queryOrdered(byChild: "name").queryEqual(toValue:"Arya)"ref呢,它指向Subjects/-math
  • 我认为这是因为您正在寻找与学生相同的科目的孩子,但找不到孩子学生,因为那是数学等科目的另一个孩子。你需要得到它来检查每个主题的孩子,即你所拥有的查询的数学。
  • Firebase 数据库查询可以按已知路径的属性进行过滤。无法像您尝试那样在动态路径上查询属性。这意味着您需要修改数据模型以允许您想要的查询,例如存储“每个学生的课程”的顶级列表。另见stackoverflow.com/questions/27207059/…

标签: swift firebase firebase-realtime-database


【解决方案1】:

也许像这样的东西......可以工作......

var subjects = [String]()

    ref.observeSingleEvent(of: .value, with: { snapshot in

        let value = snapshot.value as? NSDictionary
        let postsIds = value?.allKeys as! [String] // this will put all the subjects such as math into an array called postIDs

        for postId in postsIds { //this is going to cycle through the array and check each one for your student
            let refToPost = Database.database().reference(withPath: "Subjects" + postId)
            refToPost.observeSingleEvent(of: .value, with: { snapshot in
                if snapshot.hasChild("Arya") {



                    self.subjects.append(snapshot)
                }
            })
        }
    })
  print("this is the ist of subjects with my student: \(subjects)")

【讨论】:

  • 这可行,但不是最佳做法。为什么?因为您在这里所做的是从节点读取所有结果,然后在手机上将它们过滤掉。请记住,由于您读取了所有数据,因此您可能会读取数千个结果。你应该做的是使用queryOrdered 并且在执行查询时已经过滤了结果。这样,您只会在响应中获得很少的结果,而不是该节点内的所有结果。
  • 如果我们把refToPost.observeSingleEvent(of: .value, with: { snapshot in改成refToPost.queryOrdered(byChild: "students/name").queryEqual(toValue: "Arya").observeSingleEvent(of: .value, with: { snapshot in会怎么样
  • 这是 OP 已经拥有的。但是,是的,这是正确的做法。
  • 我已经这样做了,但是我对这个解决方案感到困扰,所以我正在寻找一种更好的方法来做到这一点。还是谢谢。
猜你喜欢
  • 1970-01-01
  • 2021-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-15
  • 1970-01-01
  • 2018-04-28
相关资源
最近更新 更多