如何使用 Firebase RealTime 数据库根据特定类别获取项目集合

Posted

技术标签:

【中文标题】如何使用 Firebase RealTime 数据库根据特定类别获取项目集合【英文标题】:How to get collection of items depending on specific category using Firebase RealTime DataBase 【发布时间】:2021-03-06 02:24:04 【问题描述】:

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

数据库

+ 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);

【问题讨论】:

【参考方案1】:

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) 并在单独的调用中获取类别详细信息。

【讨论】:

以上是关于如何使用 Firebase RealTime 数据库根据特定类别获取项目集合的主要内容,如果未能解决你的问题,请参考以下文章

如何在 swift 4.0 中获取 firebase-realtime-database 中的特定值

如何从 Firebase Realtime DB 读取孩子的值?

如何使用以 TypeScript for Firebase Realtime 数据库编写的云函数从 onCreate 触发以外的节点获取数据?

Android config firebase realtime database rule for normal user access

Flutter firebase realtime db 在规则中使用 displayName

是否可以使用 Firebase Cloud Functions on Realtime 数据库创建覆盖多个节点的原子事务?