Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Cloud Firestore Many to Many Relationships

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?

like image 697
InfoStatus Avatar asked Oct 07 '17 22:10

InfoStatus


People also ask

Can firebase handle 10 million users?

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.

How do you create a one to many relationship in firebase?

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.

Is firestore a relational database?

Firestore is a NoSQL database, meaning it is non-relational.

How many documents can be in a collection firebase?

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.


1 Answers

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!

like image 120
André Lima Avatar answered Oct 04 '22 03:10

André Lima