Yacine Yacine - 5 months ago 90
iOS Question

FIRDatabaseQuery: how to do an inner join

I'm trying to do an inner join on a FIRDatabaseQuery object.

below is the database structure. I have some posts that are linked to post-comments. I am trying to get all the posts that a specific user added a comment on:

{
"posts" : {
"-KIycKhZU55dmKnHbbxv" : {
"author" : "John Doe",
"body" : "This is a post test",
"title" : "test",
"uid" : "SHaH36BLwgPvwgi9cDmRnsnONFB2"
},
"-KIyg_ks1O5QL4_4dfq_" : {
"author" : "Jane Doe",
"body" : "This is a post test",
"title" : "test2",
"uid" : "x5leSBGArnd10JilD9YDyNBNfZ03"
},...
}
"post-comments" : {
"-KIycKhZU55dmKnHbbxv" : {
"-KIycMyL0Vy1BHVdI4zc" : {
"author" : "toto",
"text" : "test",
"uid" : "SHaH36BLwgPvwgi9cDmRnsnONFB2"
},
"-KIyg_ks1O5QL4_4dfq_" : {
"author" : "toto",
"text" : "test",
"uid" : "SHaH36BLwgPvwgi9cDmRnsnONFB2"
}
},...
}


in SQL this will be translated into a inner join query similar to:

Select * from post inner join post-comments on post-id where post-comments.uid = "user id"

Does anybody know how o get something similar to an inner join in firebase?

Thanks a lot,
Yacine

Answer

You will need to work with nested firebase calls. You can find a javascript example in this question but your swift code should look like the following:

ref.child("posts").observeEventType(.ChildAdded, withBlock: { (snapshot) in
    if let postId = snapshot.key as! String {
        ref.child("post-comments").child(postId).queryOrderedByChild("uid").queryEqualToValue(userId).observeSingleEventOfType(.Value, withBlock: { (snapshot) in
            for child in snapshot.children.allObjects as [FDataSnapshot] {
               println(child.value)     
            }
        }) { (error) in
            print(error.localizedDescription)
        }
    }
})