0

In my Firebase database, I have a data structure similar to this: firebaseDatabase

The post ID (1a3b3c4d5e) is generated by the ChildByAutoId() function. The user ID (fn394nf9u3) is the UID of the user.

In my app, I have a UILabel (author) and I would like to update it with the 'full name' of the user who created the post.

Since I have a reference to the post ID in the users part of the database, I assume there must be some code (if statement?) to check if the value exists and if so, update the label.

Can you help with that?

KENdi
  • 7,576
  • 2
  • 16
  • 31
scottc00
  • 283
  • 1
  • 2
  • 8
  • 1
    Why not simply save the name with the post so you get something like: `1a3b3c4d5e = {description:"world", title:"Hello", author:"John Smith"}` – André Kool Mar 13 '18 at 13:15

2 Answers2

0

While it is possible to do the query (ref.child("Users").queryOrdered(byChild: "Posts/1a3b3c4d5e").queryEqual(toValue:true)), you will need to have an index on each specific user's posts to allow this query to run efficiently. This is not a feasible strategy.

As usual when working with NoSQL databases: if you need to do something that your current data model doesn't allow, change your data model to allow the use-case.

In this case that can either be adding the UID of the user to each post, or alternative add the user name to each post (as Andre suggests) and determining if/how you deal with user name changes.

Having such relational data in both directions to allow efficient lookups in both directions is very common in NoSQL database such as Firebase and Firestore. In fact I wrote a separate answer about dealing with many-to-many relations.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
0

If you can change the structure then that is very good because I don't think you are maintaining proper structure for database.

You should take one more key name createdBy inside the Post node so actully structure would be

{description:"Thus the post is here", title:"Hello User", createdBy:"Javed Multani"}

Once you do this, It will dam easy to get detail of user.

OR

Unethical solution,

You can achieve this thing like while you are going to show Post from post node of firabase. Definitely you'll get the auto generated postid like: 1a3b3c4d5e

now first you should first get only posts then inside the successfully getting data and parsing you have to get users and find inside the user by putting the codition like postId == UserPostId if match found take fullname value from there.

Mr.Javed Multani
  • 12,549
  • 4
  • 53
  • 52