3

In my flutter application, I'd like to keep track of the employee location for different companies without having to flatten the database (see architecture below).

Q1 : If I set a listener on an office node, is there a way to get the parents nodes from the event ?

Q2 : if a new company node is created in the database, how can I attach dynamically a new listener on the office's new company ?

 _employeesQuery = databaseReference.reference().child("Company_1/Office_1");

_onEmployeeAddedSubscription =
    _employeesQuery.onChildAdded.listen(onEmployeeAdded);

...

onEmployeeAdded(Event event) {
   setState(() {
     String name = event.snapshot.key;
     print("New employee added $name in Office ?? in Company ??");
   });
}

database architecture

Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
christophe
  • 45
  • 3

1 Answers1

0

Firebase's documentation recommends to avoid nesting data and flatten data structure for a good reason. You are not following that advice here, and that's the reason for the mismatch between your data structure and the use-case.

Firebase child listeners work on a flat list of child nodes, they have no knowledge of a hierarchy. So in your model you can listen to all offices, and then get a childChanged when something in an office changes, or you can listen to a specific office, and then get a childAdded when a user is added to that office. If you listen to all offices, you'll have to figure out what changed yourself in your application code.

Following Firebase recommendations, I'd actually model your data as two top-level lists:

userOffices: {
  "Dan": "Company_1/Office_1",
  "Tom": "Company_1/Office_1",
  "Pete": "Company_1/Office_2",
  "max": "Company_1/Office_2"
},
officeUsers: {
  "Company_1-Office_1": {
    "Dan": true,
    "Tom": true
  },
  "Company_1-Office_2": {
    "Pete": true,
    "max": true
  }
}

The exact model might be a bit different, but the important thing here is that we've stored he data in both directions. You can now fine the users for an office, and the office for a user with a direct lookup. And you can listen to userOffices to know when a user is added to any office.

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807