快速使用firebase中的值返回键

时间:2018-08-17 11:43:33

标签: ios swift firebase firebase-realtime-database

enter image description here

我试图在Firebase中仅使用值来检索密钥。

我在Swift中工作,用于iOS

试图编写一个仅向用户提供电子邮件地址“ hey@hey.com”时希望返回“ hey”的函数

基本上拥有手头的值,并且想要检索密钥,我试图删除该条目。

有人有什么建议吗?

有点不确定。

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if (editingStyle == UITableViewCellEditingStyle.delete) {

        let friendsSelectedEmail = friendsEmailsFromFirebase[indexPath.row]
        let refToUserFriendList = fir.child("mybuddies").child(userID)
        print(friendsSelectedEmail)

        //query for the key of the email address, then use that to delete the object
        //Or is there an easier firebase method?



        self.tableView.reloadData()

    }
}

**编辑

简而言之,我只想删除此键值对,而我只能访问该值(电子邮件地址),是否可以通过单个firebase方法实现? **假设我不使用@jay发布的更好的结构。

1 个答案:

答案 0 :(得分:1)

这里的意图是使用 hey@hey.com hey 部分作为密钥。

更好的方法是使用childByAutoId创建子节点并将属性存储在该节点中。所以你的结构变成了

zCu.....
  email: "hey@hey.com"
  buddy_name: "Leroy"
  domain: "hey.com"

然后,您可以简单地在所有节点中查询等于“ hey@hey.com”的电子邮件,这将返回一个快照,其中也包含用户名(hey)和域(hey.com,如果需要)

如果您需要该查询的代码,请告诉我。请记住,Firebase是异步的,因此它实际上并没有“返回”值。您可以在查询后使用闭包内的值。

在评论中,似乎我们要删除buddy_name和电子邮件,但要离开该节点。如果该节点是已知的,则可以仅创建该引用,否则可以对其进行查询。无论哪种方式,您都将获得节点的父键

let buddyRef = parent_node_key.child("buddy_name")
let domainRef = parent_node_key.child("domain")

buddyRef.setValue("")
domainRef.setValue("")

请记住,在这种情况下我留下了电子邮件,就好像我们删除了该电子邮件一样,整个节点将消失。一个节点必须至少存在一个值。

为了更加清楚;

要创建该结构,您需要知道用作密钥的用户uid,或者如果您希望在另一个节点中使用它,请使用.childByAutoId创建密钥。

let ref = thisUsersUid  //or let ref = your_firebase.childByAutoId()
ref.child("email").setValue("hey@hey.com")
ref.child("domain").setValue("hey.com")
ref.child("buddy_name").setValue("Leroy")