试图读取在某酒店注册为“客人”的当前用户(user1)的电子邮件。所以在我的 tableView 中,会有当前用户作为客人输入的酒店列表。
- 酒店
- (自动识别)
- 姓名:马里奥
- 地址:########
- 联系方式:########
- 邮箱:########
- 唯一标识:########
- guest
- (自动识别)
- 邮箱:user1@gmail.com
- 联系方式:########
- (自动识别)
- 姓名:发现
- 地址:########
- 联系方式:########
- 邮箱:########
- 唯一标识:########
- guest
- (自动识别)
- 邮箱:user1@gmail.com
- 联系方式:########
我试过这段代码,但没有用。
var hotelRequests : [DataSnapshot] = []
override func viewDidLoad() {
super.viewDidLoad()
if let email = Auth.auth().currentUser?.email {
Database.database().reference().child("Hotels").queryOrdered(byChild: "Name").queryEqual(toValue: email).observe(.childAdded, with: { (snapshot) in
if let hotelDictionary = snapshot.value as? [String:AnyObject] {
if let nameOfHotel = hotelDictionary["name"] as? String {
} else {
self.hotelRequests.append(snapshot)
self.tableView.reloadData()
}
}
}
}
}
我想在我的 tableView 中看到当前用户 (user1) 成为客人的酒店列表。
更新代码
var hotels : [DataSnapshot] = []
var guest : [DataSnapshot] = []
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as UITableViewCell
if (tableView.tag == 1) {
if let email = Auth.auth().currentUser?.email {
Database.database().reference().child("hotels").queryOrdered(byChild: "email").queryEqual(toValue: email).observeSingleEvent(of: .childAdded, with: { (snapshot) in
let snapshot = self.hotels[indexPath.row]
if let hotelsDictionary = snapshot.value as? [String:AnyObject] {
if let typeOfhotel = hotelsDictionary["typeOfHotel"] as? String {
cell.textLabel?.text = typeOfhotel
}
}
})
}
}
else if (tableView.tag == 2) {
if let email = Auth.auth().currentUser?.email {
Database.database().reference().child("guest").queryOrdered(byChild: "guest Email").queryEqual(toValue: email).observeSingleEvent(of: .childAdded, with: { (snapshot) in
let snapshot = self.guest[indexPath.row]
if let guestDictionary = snapshot.value as? [String:AnyObject] {
if let aTypeOfguest = guestDictionary["TypeOfGuest"] as? String {
cell.textLabel?.text = aTypeOfguest
}
}
})
}
}
return cell
最佳答案
您当前的数据结构可以轻松找到给定酒店的客人。然而,它并不容易为特定客人找到酒店。
这样做的原因是 Firebase 数据库查询在列表模型上工作。因此,例如,您可以按名称或地址而不是客人来订购/过滤酒店。因此,在您当前的数据模型中,您需要读取所有酒店的所有数据,然后才能确定用户的酒店列表。
为了允许查询用户的旅馆,添加倒排数据结构:
userHotels: {
uid1: {
hotelId1: true,
hotelId2: true
},
uid2: {
hotelId2: true,
hotelId3: true
}
}
有了这个额外的数据结构,为用户加载酒店就变得微不足道了。
除了 true
,您还可以存储一些关于酒店的信息,这样您就不必在客户端代码中加入这些信息。
另见:
关于swift - 在 2 级节点内调用子节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57282697/