Firebase 中的 OR 查询 [英] OR queries in Firebase

查看:22
本文介绍了Firebase 中的 OR 查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个消息系统.我计划收集消息,然后根据发送方和接收方查询消息.为此,我需要查询例如:由 Bob 发送并由 Tony 接收的所有消息以及由 Tony 发送并由 Bob 接收的所有消息.我很不清楚如何做这个或"语句.到目前为止,我已经

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 to query for example: all messages that are sent by Bob and received by Tony and all messages that were sent by Tony and received by Bob. I am quite unclear about how to do this "or" statement. As of now I have

MessageRef.once('value', function(dataSnapshot) {
  console.log(dataSnapshot.val());
});

返回所有消息.然后我可以做一个 forEach 但它似乎不是很有效.大家有什么建议吗?

which return all messages. I could then do a forEach but it seems not very efficient. Would you guys have any suggestions?

另外,你有没有想过我构建消息系统的模型与例如聊天室相比是否好.

Also, do you have thoughts on wether my model to build that message system is good vs having chat rooms for example.

谢谢

推荐答案

Firebase 目前只能查询单个子属性.因此,如果您想查询多个属性,则必须将它们合二为一:

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?"

然后您可以使用以下命令查询从 Bob 到 Tony 的消息:

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
});

这篇关于Firebase 中的 OR 查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆