Firebase 中的多对多关系 [英] Many to Many relationship in Firebase

查看:25
本文介绍了Firebase 中的多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Firebase 数据库.我有公司和承包商.一个承包商可以为多个公司工作,一个公司可以有多个承包商.这是一个简单的多对多关系.我希望能够回答有关公司和承包商的问题:

I have a Firebase database. I have Companies and Contractors. A Contractor can work for more than one Company and a Company can have multiple Contractors. This is a straightforward many to many relationship. I want to be able to answer the questions about Companies and Contractors:

  1. 给定一家公司,他们是当前的承包商.
  2. 向承包商介绍他们为哪些公司工作.

在 Firebase 中构建数据的替代方法有哪些?

What are the alternatives for structuring the data within firebase?

推荐答案

自我回答确实是对此进行建模的一种方式.这可能是您在关系数据库中建模的最直接的等价物:

The self-answer is indeed one way of modeling this. It's probably the most direct equivalent of how you'd model this in a relational database:

  • 承包商
  • 公司
  • companyAndContractorsAssignment(多对多连接器表)

另一种方法是使用 4 个顶级节点:

An alternative would be to use 4 top-level nodes:

  • 承包商
  • 公司
  • 公司承包商
  • 承包商公司

最后两个节点看起来像:

The last two nodes would look like:

companyContractors
    companyKey1
        contractorKey1: true
        contractorKey3: true
    companyKey2
        contractorKey2: true
contractorCompanies
    contractorKey1
        companyKey1: true
    contractorKey2
        companyKey2: true
    contractorKey3
        companyKey1: true

这种双向结构允许您查找公司的承包商"和承包商的公司",而无需查询其中任何一个.这肯定会更快,尤其是当您添加承包商和公司时.

This bidirectional structure allows you to both look up "contractors for a company" and "companies for a contractor", without either of these needing to be a query. This is bound to be faster, especially as you add contractors and companies.

这对于您的应用是否必要,取决于您需要的用例、您期望的数据大小等等.

Whether this is necessary for your app, depends on the use-cases you need, the data sizes you expect and much more.

推荐阅读NoSQL数据建模并查看面向 SQL 开发人员的 Firebase.这个问题也在#AskFirebase youtube 系列的一集中出现.

Recommended reading NoSQL data modeling and viewing Firebase for SQL developers. This question was also featured in an episode of the #AskFirebase youtube series.

有人发布了一个 此处链接的后续问题 关于从承包商"和公司"节点检索实际项目.您需要一次检索这些,因为 Firebase 没有与 SELECT * FROM table WHERE id IN (1,2,3) 等效的内容.但是这个操作并不像你想象的那么慢,因为请求是通过单个连接管道传输的.在此处阅读更多相关信息:通过使用查询而不是重复观察单个事件来加快为我的社交网络应用获取帖子.

Somebody posted a follow-up question that links here about retrieving the actual items from the "contractors" and "companies" nodes. You will need to retrieve those one at a time, since Firebase doesn't have an equivalent to SELECT * FROM table WHERE id IN (1,2,3). But this operation is not as slow as you may think, because the requests are pipelined over a single connection. Read more about that here: Speed up fetching posts for my social network app by using query instead of observing a single event repeatedly.

这篇关于Firebase 中的多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆