加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – Firebase查询

发布时间:2020-12-14 05:40:08 所属栏目:百科 来源:网络整理
导读:假设我有这样的结构: -users -user1_uid name distance age 我如何进行查询(查找距离100且年龄介于20到25之间的用户)? 我试过标准方法 let recentPostsQuery = (ref?.child("users").queryOrderedByChild("age").queryStartingAtValue("20"))! 问题是,这似
假设我有这样的结构:
-users
  -user1_uid
    name
    distance
    age

我如何进行查询(查找距离<100且年龄介于20到25之间的用户)? 我试过标准方法

let recentPostsQuery = (ref?.child("users").queryOrderedByChild("age").queryStartingAtValue("20"))!

问题是,这似乎不可能查询多个孩子(如结合年龄和距离过滤).几个月前与Firebase相比,这方面有什么变化吗?我相信,在第一次查询后在本地过滤它们不是一种选择,因为可能存在数千个对象.

我的第一选择是查询20到25之间的所有用户,然后在代码中过滤距离<1的用户. 100. 问题表明,代码中的过滤不是一种选择,但我想将其包含在完全适用于数千个节点或更少节点的情况中:
struct User { //starting with a structure to hold user data
        var firebaseKey : String?
        var theAge: Int?
        var theDistance: Int?
    }

    var userArray = [User]() //the array of user structures

    usersRef.queryOrderedByChild("age").queryStartingAtValue(20)
     .queryEndingAtValue(25).observeEventType(.Value,withBlock: { snapshot in

        for child in snapshot.children { //.Value so iterate over nodes

            let age = child.value["age"] as! Int
            let distance = child.value["distance"] as! Int
            let fbKey = child.key!

            let u = User(firebaseKey: fbKey,theAge: age,theDistance: distance)

            userArray.append(u) //add the user struct to the array
        }

        //the array to contain the filtered users
        var filteredArray: [User] = []
        filteredArray = userArray.filter({$0.theDistance < 100}) //Filter it,baby!

        //print out the resulting users as a test.
        for aUser in filteredArray {

            let k = aUser.firebaseKey
            let a = aUser.theAge
            let d = aUser.theDistance

            print("array: (k!)  (a!)  (d!)")

        }

    })
}

现在一个潜在的超简单答案.

let usersRef = self.myRootRef.childByAppendingPath("users")

    usersRef.queryOrderedByChild("age").queryStartingAtValue(20)
     .queryEndingAtValue(25).observeEventType(.ChildAdded,withBlock: { snapshot in

        let distance = snapshot.value["distance"] as! Int

        if distance < 100 {
            let age = snapshot.value["age"] as! Int
            let fbKey = snapshot.key!

            print("array: (fbKey)  (age)  (distance)")
        }
    })

请注意,我们正在利用.ChildAdded而不是.Value,因此每次读取一个节点 – 如果距离不是我们想要的,我们可以忽略它并继续下一个节点.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读