首页 > 解决方案 > 如何使用 Firebase RealTime 数据库根据特定类别获取项目集合

问题描述

我有一个由实时数据库 firebase 中的两个表或集合组成的应用程序,[coupons, categories]我想获取属于特定类别 ID 的所有优惠券,我该如何获取这些数据?所以我的意思是one to many在firebase中实现关系

数据库

+ categories
  - 1605426969
    - count: 0
    - createdDate: 1605426969
    - id: 1605426969
    - imageUri: "https://placeholder.png"
  - 160542456
    - count: 0
    - createdDate: 1605426969
    - id: 160542456
    - imageUri: "https://placeholder.png"
    
+ coupons
  - 1605515952
    - category
      - 1605426969
      - count: 0
      - createdDate: 1305426969
      - id: 1605426969
      - imageUri: "https://placeholder.png"
    - code: "L1150" 
    - description: "my description"
    - id: 1605515952
    - imageUri: "https://avatar.png"
    -url: "https://www.google.com/"
 - 16055151325
    - category
      - 1605426969
      - count: 0
      - createdDate: 1305426969
      - id: 1605426969
      - imageUri: "https://placeholder.png"
    - code: "L1150" 
    - description: "my description"
    - id: 16055151325
    - imageUri: "https://avatar.png"
    - url: "https://www.google.com/"

所以我试图像下面那样获取它,但它不起作用,你能帮我吗?


//...
const app = Firebase.initializeApp(firebaseConfig)
const categoryRef = app.database().ref().child('categories')
const couponRef = app.database().ref().child('coupons')

const coupons = couponRef.orderByChild('category').equalTo('1605426969');

console.log(coupons);

标签: javascriptfirebasevue.jsfirebase-realtime-database

解决方案


Firebase 实时数据库是一个面向文档的数据库。因此,您不能真正定义一对多关系。他们确实描述了您应该如何扁平化数据,或多或少做同样的事情:https ://firebase.google.com/docs/database/web/structure-data#flatten_data_structures 。

它基本上归结为使用明确的标识符并进行单独的调用以获取所需的数据。


在您的情况下,您可以存储优惠券,例如:

+ coupons
  - 1605515952
    - category_id: 1605426969
    - code: "L1150" 
    - description: "my description"
    - id: 1605515952
    - imageUri: "https://avatar.png"
    -url: "https://www.google.com/"

.where(category_id: 1605426969)然后在单独的调用中查询并获取类别详细信息。


推荐阅读