FIRDatabaseQuery: how to do an inner join

后端 未结 2 1377
有刺的猬
有刺的猬 2021-01-14 06:50

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

相关标签:
2条回答
  • 2021-01-14 07:16

    You may want to consider

    "posts" : {
        "-KIycKhZU55dmKnHbbxv" : {
          "author" : "John Doe",
          "body" : "This is a post test",
          "title" : "test",
          "uid" : "SHaH36BLwgPvwgi9cDmRnsnONFB2"
          "commented_by"
               "SHaH36BLwgPvwgi9cDmRnsnONFB2": true
    

    Then you can simply query for

    posts.child("commented_by/uid").queryEqualToValue(true)
    

    or, change the post-comments around to better match the queries you want to do:

    "post-comments" : {
      "-KIycMyL0Vy1BHVdI4zc" : {
         "author" : "toto",
         "post_data":
              post_id: "-KIycKhZU55dmKnHbbxv",
              post_title: "test"
         "text" : "test",
         "uid" : "SHaH36BLwgPvwgi9cDmRnsnONFB2"
    },
    

    That makes the query a snap as the post-comments node can be queried for the uid which return all of the post_id's of the posts they commented on. It wouldn't return the post itself, however, you may just be looking for the title so you can populate a list. Once the user taps it clicks it you can retrieve the actual data.

    0 讨论(0)
  • 2021-01-14 07:29

    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)
            }
          }
    })
    
    0 讨论(0)
提交回复
热议问题