SatelBill
SatelBill

Reputation: 731

How to get direct parent's key in Firebase real-time database?

Now I am building a React ecommerce website. And now I am in the cart page. In the cart page, if user click the first product, I want to show all rest 2 products products. How to get all products of special store that has special id as key? In the image, I want to get 3 red right arrows' products.

enter image description here

Upvotes: 0

Views: 125

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598740

I don't think that is currently possible. With your current data structure you can easily find the products for a known store ID, but not the store ID for a known product ID.

The reasons is that orderByKey() requires that the keys are directly under the path you query, and you don't know the store ID, and orderByChild() requires that the value lives at a known/fixed path under each direct child node of the path, which also isn't the case here.

The common approach is to create a reverse data structure, where you map product IDs to store IDs.

That could like like this (if each product has a single store):

ProductStores: {
  "-M_ProductId": "A4_StoreId"
}

And like this (if each product can exist in multiple stores):

ProductStores: {
  "-M_ProductId": {
    "A4_StoreId": true,
    "A5_StoreId": true
  }
}

Also see:

Upvotes: 1

Related Questions