OR queries in Firebase

前端 未结 1 499
执念已碎
执念已碎 2020-11-27 08:08

I am trying to build a message system. I am planning on having a collections of messages and then querying messages based on sender and receivers. In order to do so I need t

相关标签:
1条回答
  • 2020-11-27 09:03

    Firebase currently can only query on a single child property. So if you want to query multiple properties, you'll have to combine them into one:

    Messages
      -DFHJ3498ua
        from: Tony
        to: Bob
        from_to: Tony_Bob
        message: "Hello Bob, this is Tony"
      -DFHJ3598uz
        from: Bob
        to: Tony
        from_to: Bob_Tony
        message: "Hello Tony, What can I do for you?"
      -EFHJ3498ua
        from: Tony
        to: Bob
        from_to: Tony_Bob
        message: "Can you help me with this Firebase query?"
    

    You can then query for messages from Bob to Tony using:

    var ref = new Firebase('https://your.firebaseio.com/Messages');
    var query = ref.orderByChild('from_to').equalTo('Bob_Tony');
    query.on('value', function(snapshot) {
      console.log(snapshot.val()); // all messages from Bob to Tony
    });
    

    In a chat-like application, you might want to consider actually using the sender-receiver pair as the key:

    Messages
      from_Bob_to_Tony
        -DFHJ3598uz
          from: Bob
          to: Tony
          message: "Hello Tony, What can I do for you?"
      from_Tony_to_Bob
        -DFHJ3498ua
          from: Tony
          to: Bob
          message: "Hello Bob, this is Tony"
        -EFHJ3498ua
          from: Tony
          to: Bob
          message: "Can you help me with this Firebase query?"
    

    With this data structure you won't have to run a query to get the relevant messages, but can do a direct lookup.

    var ref = new Firebase('https://your.firebaseio.com/Messages');
    var query = ref.child('from_Bob_to_Tony');
    query.on('value', function(snapshot) {
      console.log(snapshot.val()); // all messages from Bob to Tony
    });
    
    0 讨论(0)
提交回复
热议问题