Confused about Firebase query implementation

98 Views Asked by At

I am new to firebase and I need help with this please. I have two nodes in my database: users and posts as shown below:

users
    uid
      name: "William"
      post:
          KUhyPi5xLZBGyp-_X-W: true
         -KWH8EVxohgNBfHuKoYy: true

posts
    KUhyPi5xLZBGyp-_X-W     
                 comment: "I love this"
   -KWH8EVxohgNBfHuKoYy     
                 comment: "Coding is fun"

Currently I am able to display all the posts in tableView. But I want to be able to display the name of the user who made the post just like in facebook. Please advise me how to retrieve the username of who made a particular post at that indexpath so as to display it in a label in the tableViewcell

Here is code I am using to show all posts in the tableview currently

  DataService.ds.REF_POST.observe(
        .value, with: { (snapshot) in
            if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot]{
                for snap in snapshot{
                    print("SNAP: \(snap)")
                    if let postDict = snap.value as? Dictionary<String, AnyObject>{

                        let key = snap.key
                        let post = Post(postKey: key, postData: postDict)
                        self.posts.append(post)
                    }
                }
            }
            self.tableView.reloadData()
    })

}
1

There are 1 best solutions below

3
On

When you save your comments, store the uid along with it so that you can easily query for it later.

{
    "posts" : {
        "KUhyPi5xLZBGyp-_X-W": {
            "uid": "USER_ID",
            "comment": "I love this"
        }
        "-KWH8EVxohgNBfHuKoYy": {
            "uid": "USER_ID",
            "comment": "Coding is fun"
        }
    }
}

I realise this looks like duplicating your data but this is how they recommend you store the data so that you can easily/quickly query it. For instance once you get all yoru comments you would then gather up all the user ids and go get those individual users. There isn't a way to do this all in one query.