Android - Database Structure (Firebase)

前端 未结 1 503
说谎
说谎 2021-01-28 09:19

I have an application where I have three usertypes: \"The school\", \"Older Students\", and \"Younger kids\". The school makes different routes on a map and ass

相关标签:
1条回答
  • 2021-01-28 09:41

    It sounds like the relationships between these objects could be summarized as:

    • A school contains many routes, markers and users
    • A route has a one-to-many relationship with markers
    • A marker has a one-to-one relationship with a route
    • A user has a one-to-many relationship with markers and routes

    As we know, the Firebase Realtime Database is a NoSQL database and therefore doesn't explicitly support relationships, but they can be inferred in the structure, so take this structure for example (where ... is your existing values):

    schoolId
      users
        userId
          ...
      markers
        markerId
          ...
          route      // the route ID that this marker belongs to
      routes
        routeId
          ...
          markers    // list of marker IDs that belong to this route
    

    Note: To keep this example simple, I'll ignore the users relationships for now and just work with the relationships between markers and routes.

    With this structure: whether we are currently working with a marker or a route, we can easily find out how they relate to each other.

    It is then easy to get all markers related to a specific route by performing a query against the route value of children in the markers node:

    schoolReference.child("markers").orderByChild("route").equalTo(routeId);
    

    Where routeId is the unique ID of the route we are currently working with.

    You'll need to be aware of some changes when creating objects though, so for example, when you create a marker with this structure, you'll need to:

    • Set the route value of the marker to the the ID of the route that it belongs to, and
    • add the marker ID to the markers list under the route that it belongs to.

    You can achieve this in one write operation using a transaction or a multi-location update.

    Note: You don't actually have to use the routeId/markers list, but it can be useful if you're using FirebaseUI to display indexed data.

    This technique of using IDs as index keys is called data fan out and you can read more about it in the structure your database documentation.

    0 讨论(0)
提交回复
热议问题