denis eldorado
denis eldorado

Reputation: 73

how to access related data in firebase

I'm new to Firebase. I have read alot of articles about structuring my data for faster loading. I have already understood the logic. however I want further explanation on this.

Suppose I am creating a app where I have two entities: users and products.

User can post alot of products. it's a one to many relationship. I have read that for better perormance I have to duplicate my data(denormalization) so my database would look like this:

  users:
{
"user1":
 {
  name: "denis",
  phone: "09898989083"
  .........more data here
 }

 products:{
   "product1": true,
   "product2":true
  }
}

"products"
{

 "product1":

{

  name: "iphone6",
  price: "500 USD"
}

 "product1":

{

name: "samsung",
price: "400 USD"
 }

}

My question is in my users table, on the relationship with product am told to put the product ID then I set the value to true. what does this true do. how do I fetch the name and price of that product in ANdroid for example using that true?

Upvotes: 1

Views: 728

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 139039

As you said, denormalization is a common practice within Firebase. I'll give you an example to understand better what it means. Many developers with a SQL background would structure the database like this:

Firebase-root
   --- Users
     --- User1
       --- name: "denis"
       --- phone: "09898989083"
       --- Products
         --- Product1
           --- name: "iphone6"
           --- price: "500 USD"
         --- Product2
           --- name: "iphone5"
           --- price: "300 USD"

As you see, the Products node is nested under each user node. This means that every time you want to get some details of a particular user, you need to download the enitire node of that user, including products details, which is obvious are not necessary. So, when it comes to Firebase, we use denormalization. This means that inside a user node we use just product1": true to know that a particular product belongs to that user. Knowing the id of the product, we can get all the necessary details of that product. Another thing to keep in mind is that we need to have the database as flatten as we can. For that, i recomand you read the following post, Structuring your Firebase Data correctly for a Complex App.

Hope you'll understand better this concept.

Upvotes: 1

Related Questions