Firebase database diagram

Issue

I’m trying to do a sample app where I have some users and then I have another table named products, and each product is assigned to a user I’m creating this diagram but I’m not sure if it’s optime

Users
     |
     |--------user1_id
     |         | 
     |         |--name : "user1"
     |         
     |          
     |
     |---------user2_id
               | 
               |--name : "user2"
                

Then I have Product

Products     
             |--------product1_id
             |         | 
             |         |--image: "any_value"
             |          --name:  "any_value"
             |         
             |
             |---------product2_id
                       | 
                       |--image: "any_value"
                       |--name:  "any_value"

The problem is that I’m not sure how to assign that product to an user, the thing is that I want to create first the firebase first (by hand if possible) and then do the app, because I remember long time ago I had to create the products and the users by code.

So the problem is, do I need another table where I have productid + userid?

Demo

There are 4 users
-Bob
-Annie
-Perl
-Kuy

There are 4 products
-Prod1
-Prod2
-Prod3
-Prod4

And Prod1 is from Bob, Prod2 is from Annie, Prod3 is from Perl and Prod4 is from Kuy.

Solution

If you need to assign a product to a user, then you should simply add the UID of the user as a field inside the product object. So your schema should look like this:

db-root
 |
 --- users
 |     |
 |     --- user1_id
 |          |
 |          --- name: "user1"
 |
 --- products
       |
       --- product1_id
            |
            --- image: "any_value"
            |
            --- name: "any_value"
            |
            --- uid: "user1_id" //👈

Now to get the products that correspond to user1, you have to perform a query that looks like this:

val db = Firebase.database.reference
val productsRef = db.child("products")
val queryByUid = productsRef.orderByChild("uid").equalTo("user1_id")
queryByUid.get().addOnCompleteListener {
    if (it.isSuccessful) {
        val snapshot = it.result
        for (productSnapshot in snapshot.children) {
            val productName = productSnapshot.child("name").getValue(String::class.java)
            Log.d("TAG", productName)
        }
    } else {
        Log.d("TAG", error.getMessage())
    }
}

Answered By – Alex Mamo

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *