rachelvsamuel
rachelvsamuel

Reputation: 1721

In Firebase can I connect a user to multiple tables?

I have two tables in my Firebase database. In flighthistory I record flights that a plane has taken. In flightperformance I record how well each plane can perform.

I think there should be a third table with the planes' names and IDs, and that the planes should be assigned their ID in flighthistory and flightperformance.

Is this the right way to think about coordinating between two tables of data? How can I code this with Firebase?

Upvotes: 1

Views: 4064

Answers (1)

Remi Rønning
Remi Rønning

Reputation: 58

If i understand correctly, you want three tables: 1: Plane names and ID's. 2: Flighthistory. 3: Flightperformance.

And instead of having the plane id from table 1 as a foreign key in table 2 and 3 (as it would be in an sql database), you want the same "solution" in firebase?

If so: Create a Plane table that holds all the planes. When you create a new plane, the key you will get (by using the getkey()) will be the ID in firebase for that specific plane. You can use the same key as a reference in Flighthistory and Flightperformance to connect the plane with the history and performance tables.

The Firebase "tables" will be like this:

  • Plane -> the ID's / keys for each plane -> Plane name and model(maybe?).

  • FlightHistory -> You could use the same ID / key here for the plane -> Some flight history data. A good solution here would either be using some kind of an auto increment (Or date + time maybe?), and inside this number, there will be data as in where the plane came from, and the destination.

  • Flightperformance -> Same ID here for each plane -> Some flight performance data.

EDIT: A little example of how this could be done:

//Get the firebase database reference in onCreate(). For this example, mDatabase will be the databasereference

public void createPlane() {
    //First getting the key which will be used as the reference between the tables
    String key = mDatabase.child("Planes").push().getKey();

    //Create a new plane
    Plane plane = new Plane("Coolplane", "Boeing 777-400");

    //Adding the plane to firebase, with the key as the reference
    mDatabase.child("Planes").child(key).setValue(plane);

    //Starting the methods that create the flighthistory and performance.Passing the key, which will be used as the ID in firebase (which connects the plane with the history and performance
    newFlightHistory(key);
    newPerformance(key);

//Not sure how your history and/or performance table will look like, but you 
just pass the key to these methods, and use these keys as the key when you 
create a new history / performance. 

}

NB: As Firebase is a JSON based db, it is usually not a "correct" way to structure the data. It all depends on what queries you are going to use, and how you are going to use the data.

Upvotes: 3

Related Questions