Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get data within firebase, when we have many to many relationship

I read this question Many to Many relationship in Firebase,
and here describes how to create or structure many to many relationship within firebase(nosql database), and it is pretty easy,

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

but when i want to get all contractors specific company, can i do it using only one request? because in this case i get only list of id, and after there, using js loop, or forEach, i do multiple request.

usually on others API's, i only use

URL/contractor/:id/company or 
URL/company/:id/contractors 

how to do it on firebase?
it would be cool to have an example of using angular2, angularfire2
thanks

AskFirebase

like image 234
Limarenko Denis Avatar asked Oct 30 '22 13:10

Limarenko Denis


1 Answers

With NoSQL, you have to think in terms of views first, then let the views dictate your schema. You can definitely do this with one query, but forget about normalization, that concept only applies to relational databases.

Let's say you have a view where you want to search by company and list all the contractors, with their info, or search by contractor and list all the companies with their info:

Schema: companyContractorKey, contractorCompanykey, contractorName, contractorSkill, companyIndustry, etc...

where companyContractorKey is a field containing a concatenation of the company name and contractor name, for example: 'Acme/Ellis Electric'. You can then do a range search from 'Acme/A' to 'Acme/z' and get all the contractors for Acme.

Similarly, contractorCompanyKey is a field containing a concatenation of the contractor name and company, for example 'Ellis Electric/Acme'. You can then do a range search from 'Ellis Electric/A' to 'Ellis Electric/z' to get all the companies for Ellis Electric.

The drawback is that the information for a company is stored in multiple records (easily found using the companyContractorKey), and the information for a contractor is also stored in multiple records (found using the contractorCompanyKey), so updates and deletions will involve multiple records, but querying will be super fast, as long as you indexOn the two key fields. Firebase supports updating multiple records with one request, so this should not present a problem.

Also you will want to avoid putting in all the information about a company or contractor in that schema node, only what is necessary for your views, and have all the details that are not in the "listing" view in separate schema nodes, one dedicated to companies and one to contractors.

like image 166
Tony BenBrahim Avatar answered Nov 15 '22 06:11

Tony BenBrahim