【问题标题】:Query Firebase Database for multiple keys查询多个键的 Firebase 数据库
【发布时间】:2017-10-13 16:00:29
【问题描述】:

我刚刚开始使用 Firebase 数据库,在高效查询数据方面遇到了一些麻烦。我当前的数据库结构类似于推荐数据结构的 Firebase 文档,我们在其中看到了这个示例:

// An index to track Ada's memberships
{
  "users": {
    "alovelace": {
      "name": "Ada Lovelace",
      // Index Ada's groups in her profile
      "groups": {
         // the value here doesn't matter, just that the key exists
         "techpioneers": true,
         "womentechmakers": true
      }
    },
    ...
  },
  "groups": {
    "techpioneers": {
      "name": "Historical Tech Pioneers",
      "members": {
        "alovelace": true,
        "ghopper": true,
        "eclarke": true
      }
    },
    ...
  }
}

我遇到的问题是我不确定如何有效地检索特定用户的所有组名。我可以轻松检索用户的所有组 ID:

usersRef.child("alovelace").child("groups").observeSingleEvent(of: .value, with: { (snapshot) in 
// code to store group IDs 
})

但现在我能想到获取所有组名的唯一方法是通过 ID 进行 for 循环,然后为每个组调用 .observeSingleEvent 以获取名称。但是,如果我有一组非常大的用户组怎么办?理想情况下,我不希望进行如此多的数据库调用,而只需一次调用即可。这种数据结构可以吗?

【问题讨论】:

  • Firebase 将通过单个打开的连接检索项目,因此连接的开销很小。以这种方式(也称为客户端连接)检索合理数量的项目并不像您想象的那么慢,因为请求是通过现有连接进行管道传输的。见stackoverflow.com/questions/35931526/…

标签: ios swift firebase firebase-realtime-database


【解决方案1】:

这是我建议你做的。这将使用用户所属的组树中的所有数据填充组数组。

import UIKit
import Firebase

class TableViewController: UITableViewController {

    var groups = Array<Group>()

    override func viewDidLoad() {
        super.viewDidLoad()

        Group.get(userUID: "alovelace") { (groups) in

            for uid in groups {

                Group.get(groupUID: uid, completion: { (group) in

                    if let group = group {

                        print(group)

                        self.groups.append(group)

                    } else {

                        print("There is no group with id: \(uid)")
                    }

                    self.tableView.reloadData()
                })
            }
        }
    }
}

struct Group {

    var uid: String

    var name: String

    var members: Array<String>

    init?(uid:String, dict:Dictionary<String,Any>){

        guard

            let name = dict["name"] as? String,

            let users = dict["members"] as? Dictionary<String,Bool>

        else {

            return nil
        }

        self.uid = uid

        self.name = name

        self.members = Array<String>()

        for (id, _) in users {

            self.members.append(id)
        }
    }

    // Returns a Group, when given a group id.
    static func get(groupUID:String, completion: @escaping (Group?) -> ()) {

        let ref = FIRDatabase.database().reference().child("groups").child(groupUID)

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

            if let value = snapshot.value as? Dictionary<String,Any> {

                if let group = Group(uid: groupUID, dict: value) {

                    completion(group)

                    return

                } else {

                    print("Incomplete Group Data")
                }
            }

            completion(nil)
        })
    }

    // Returns the group ids that a user belongs to
    static func get(userUID:String, completion: @escaping (Array<String>) -> ()) {

        let ref = FIRDatabase.database().reference().child("users").child(userUID).child("groups")

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

            if let value = snapshot.value as? Dictionary<String,Any> {

                completion(value.keys.sorted())

                return
            }

            completion([])
        })
    }
}

【讨论】:

    【解决方案2】:

    你可以这样做:

    usersRef.child("alovelace").child("groups").observeSingleEvent(of: .value, with: { (snapshot) in 
        let result = snapshot.children.allObjects as? [FIRDataSnapshot]
        for child in result {
            let groupName = child.key
            print(groupName)
        }
    })
    

    【讨论】:

    • 当我进入(ds1 as!FIRDataSnapshot)时,没有键。据我了解,此快照仅引用我指定的路径(在用户中),因此那里没有组名。我错过了什么吗?
    • 对不起上一个答案,这个应该可以工作我编辑了它。
    • 这将返回“alovelace”-“name”、“groups”下的键名。我希望返回“组”下项目的实际名称 - 在本例中为“Historical Tech Pioneers”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 2016-10-09
    • 2018-01-25
    • 1970-01-01
    相关资源
    最近更新 更多