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 straight
After further research, I'm going to try and answer my own question. I have reviewed a number of other posts and one solution to the many-to-many problem is to store a list of ContractorKeys within a Company object and store a list of CompanyKeys within each contractor object. This is illustrated with an example below.
companies : {
companyKey1 : {
name : company1
...
contractors : {
contractorKey1 : true,
contractorKey3 : true
}
}
companyKey2 : {
name : company2
...
contractors : {
contractorKey2 : true,
}
}
}
contrators : {
contractorKey1 : {
name : bill
...
companies : {
companyKey1 : true
}
}
contractorKey2 : {
name : steve
...
companies : {
companyKey1 : true
}
}
contractorKey3 : {
name : jim
...
companies : {
companyKey2 : true
}
}
}
This organization "works" in the sense that the aforementioned questions can be answered. But a downside of this solution is that there are two lists to maintain when the Contractor/Company assignments change. It would be better if there was a way to represent this information in a single list.
I think I have come up with a better solution. The solution is to create a third list, in addition to companies and contractors called companyAndContractorAssignment. The elements of this list will represent a relationship between a single contractor and company. Its contents will be a pair of fields, the contractorKey and the companyKey. We can then eliminate the contractors list within company and the companies list within contractor. This alternative structure is represented below. Notice there is no contractor list within a company object and no companies list with a contractor object.
companies : {
companyKey1 : {
name : company1
...
}
companyKey2 : {
name : company2
...
}
}
contrators : {
contractorKey1 : {
name : bill
...
}
contractorKey2 : {
name : steve
...
}
contractorKey3 : {
name : jim
...
}
}
companyAndContractorsAssignment : {
key1 : {
contractorKey1 : true,
companyKey1: true,
}
key2 : {
contractorKey3 : true,
companyKey1: true,
}
key3 : {
contractorKey2 : true,
companyKey2: true,
}
This alternative structure allows one to answer the questions using an orderByChild/equalTo query on companyAndContractorsAssignment to find either all companies for a contractor or all contractors for a company. And there is now only a single list to maintain. I think this is the best solution for my requirements.