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:
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?
The limit you're referring to is the limit for the number of concurrently connected users to Firebase Realtime Database on the free Spark plan. Once you upgrade to a payment plan, your project will allow 200,000 simultaneously connected users.
Each Job can contain many Items and one Item must be contained by a single job (Simple One to Many). My present database structure is that both Item and Job are top level lists in firebase and each Item contains the jobKey to which it belongs. This allows me to find all items in a job as long as I know the job key.
Firestore is a NoSQL database, meaning it is non-relational.
10 for single-document requests and query requests. 20 for multi-document reads, transactions, and batched writes. The previous limit of 10 also applies to each operation.
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
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With