且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

FIRDatabaseQuery:如何做一个内部连接

更新时间:2023-11-03 23:48:28

您需要使用嵌套的Firebase调用。你可以在这个问题中找到一个 javascript示例,但是你的swift代码应该看起来像下面这样:

$ p $ ref.child(posts)。observeEventType(.ChildAdded,withBlock:{(snapshot)in
如果让postId = snapshot.key as!字符串{
let commentsRef = ref.child(post-comments)
commentsRef.child(postId).queryOrderedByChild(uid)。 queryEqualToValue(userId).observeSingleEventOfType(.Value,withBlock:{(snapshot)in
for snapshot.children.allObjects as [FDataSnapshot] {
print(child.value)
} $
print(error.localizedDescription)
}
}
})

}){预范信息的范讯范范辛辛预辛

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

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 {
      let commentsRef = ref.child("post-comments")  
      commentsRef.child(postId).queryOrderedByChild("uid").queryEqualToValue(userId).observeSingleEventOfType(.Value, withBlock: { (snapshot) in
            for child in snapshot.children.allObjects as [FDataSnapshot] {
               print(child.value)     
            }
        }) { (error) in
            print(error.localizedDescription)
        }
      }
})