Yoel Jimenez del valle
Yoel Jimenez del valle

Reputation: 1278

how to extract all child in firebase with certain part of the id iqual to some string

having this firebase structure how do i retrive only the childs of chats that child key have almost the current user id. the chats child id are like this 11-126

so let say mi user id us 11. i want to retrive all child with all it data that have 11 in any side of - . if there is a child with 89-11 o 253-11 o 11-254 i want to retrive all of those childrens. now i'm retriving all child and watching if key contains the id im interested whit this code.

chatsRef.observe(.childAdded, with: { [weak self] snapshot in
        if snapshot.key.contains(String(requestManager.instance.user.id!)){
            if let data = snapshot.value as? [String: Any]{
                let id = data["id"] as! String
                let name = data["name"] as! String
                let message = data["body"] as? String
                let senderId = data["senderId"] as! String
                let url = self?.rootRef.child("user").child(senderId).value(forKey: "url") as? String

            }
        }
    })

afer the conversion to Dictionary I got an error.

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an optional value.

the data value is this.

enter image description here seem to be that data["0"].value wourl work but it does not. Any idea how to extract all the values of the child added

Upvotes: 0

Views: 169

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599956

It sounds like you want to retrieve all chats for user 11, which means that either senderId or recipientId is 11. This type of OR query is not possible with the Firebase Realtime Database, which only supports queries on a single property.

Instead, add a data structure to your JSON that holds the chat room IDs for each user ID. So:

"userChats": {
  "11": {
    "11-126": true
  } 
  "126": {
    "11-126": true
  }
}

With this additional data structure you can easily look up the chat rooms for a user under /userChats/$uid and then load the individual chat rooms for them.

Upvotes: 0

Related Questions