Firebase Cloud Firestore多对多关系 [英] Firebase Cloud Firestore Many to Many Relationships
问题描述
如何以多对多关系构造和查询Firebase Cloud Firestore中的数据?
How to structure and query data from Firebase Cloud Firestore in a many to many relationship?
我有公司和承包商.一个承包商可以为多个公司工作,而一个公司可以有多个承包商.这是直接的多对多关系.我希望能够回答有关公司和承包商的问题:
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:
给出一个公司,他们是当前的承包商.给承包商一个他们要工作的公司.在Cloud Firestore中构造数据的正确方法是什么?
Given a Company, who are the current Contractors. Given a Contractor what Companies are they working for. What is the right way for structuring the data within Cloud Firestore?
推荐答案
您可以拥有带有地图字段的Contractor承包商项目,该地图字段的密钥为公司密钥,并且值可以是真,也可以是时间戳以帮助订购.并且公司的地图字段以承包商的钥匙作为钥匙并具有一定的价值. https://firebase.google.com/docs/firestore/solutions/中提到了此方法数组,当您尝试对它们进行过滤和排序时...
You can have Contractors item with a map field which has the key as the company key and the value can be true ou a timestamp to help ordering. And Companys with a map field with the contractors key as the key and some value. This aproach is mentioned in https://firebase.google.com/docs/firestore/solutions/arrays, when you try to filter and sort toghether...
Contractors
companies
idCompany1: timestamp
idCompany2: timestamp
idCompany3: timestamp
Companies
contractors
idContractor1: timestamp
idContractor2: timestamp
在这种情况下,您可以进行任何查询,例如该公司承包商或该承包商的公司.像这样:
Is this case you can make any queries like this company contractors or the companies of this contractor. Like this:
fireStore.collection("Companies").whereField("contractors." + idContractor, isGreaterThan: 0).order(by: "contractors." + idContractor, descending: true)
是的,您必须在任何任务中同时更新两个地方
Yes you have to update both places in any task
希望这会有所帮助!
这篇关于Firebase Cloud Firestore多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!