javascript - 如何使用 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);
解决方案
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)
然后在单独的调用中查询并获取类别详细信息。
推荐阅读
- awk - Bash命令从多个文件打印偶数列
- php - Laravel 7,运行 artisan config cache 命令崩溃并出现错误“LogicException:您的配置文件不可序列化。”
- javascript - 需要帮助:错误:无效的挂钩调用。Hooks 只能在函数组件的主体内部调用
- python - 重复的 Django ORM 查询 n+1
- azure - 在 Azure 管道中使用独立安装程序时如何运行空手道测试?
- vue.js - 将组合值传递给 v-model
- google-apps-script - 多行/多链接单元格中的自动超链接
- python - 使用 sympy 对时间求导
- html - 当href contians doPostBack() 在网页中循环浏览页码
- python - 如何实现 GRiS 均值和偏差