2

I have data stored in firebase in the following structure (figure 1). I followed the guidelines for structuring data and saved it in a flat structure with key-val pairs on events and users to allow for a many to many relationship reference. I want to user a userid to look up events that a user has access to, in pure javascript this is simple (see figure 2) however it is proving difficult with angularfire as I'd like to use a firebaseObject or array. Does anyone know how to perform a query like this?

Figure 1.

{
  users: {
      user_id1: {
         events: {
            event_id1: true,
            event_id2: true
         }
      },
      user_id2: {
         events: {
            event_id3: true,
            event_id4: true
         }
      },
      user_idN...
  },
  events: {
    event_id1: {
        users: {
           user_id1: true
         }
    },
    event_id2: {
        users: {
           user_id1: true
         }
    },
    event_idN...
  }
}

Figure 2

// List all of user_id1's events
var ref = new Firebase("https://<<example>>.firebaseio.com/");
// fetch a list of user_id1's events
ref.child("users/user_id1/events").on('child_added', function(snapshot) {
  // for each event, fetch it and print it
  String groupKey = snapshot.key();
  ref.child("events/" + groupKey).once('value', function(snapshot) {
    console.log(snapshot.val());
  });
});
anauleau
  • 35
  • 6

1 Answers1

1

This is a great case for using $extend in AngularFire.

You're sharing the $event_id key so can load the events after, the user is retrieved.

app.factory("UserFactory", function($firebaseObject) {
  return $firebaseObject.$extend({
      getEvent: function(eventId) {
        var eventRef = new Firebase('<my-firebase-app>/events').child(eventId);
        return $firebaseObject(eventRef);
      }
   });
});

app.controller('MyCtrl', function($scope, UserFactory) {
  var userRef = new Firebase('<my-firebase-app>').child("users/user_id1/");
  var user = new UserFactory();
  $scope.event = user.getEvent(user.events.event_id1);
});

See the API reference for more information.

David East
  • 31,526
  • 6
  • 67
  • 82
  • Thanks, will test it out later today. I am dealing with multiple events but I assume I can pass each event obj to an array. – anauleau Dec 27 '15 at 18:25