3

我想使用 Firebase 通过对话进行群聊。

我有下表:

Chat
- id
- from
- to
- message
- date

我想使用 Firebase 来实现以下 SQL 查询:

  1. SELECT * FROM chat where id = 'XX' order by date

  2. SELECT * FROM chat GROUP BY id ORDER BY date

如何使用 Firebase 做到这一点?

我在想,要做到#1,我可以这样做:

var chatMessagesRef = new Firebase(‘MY.firebaseio.com/chat_messages/chat_id’);
chatMessagesRef.on(‘child_added’, function(snap) {
  console.log( snap.val() );
});

但是我该怎么做#2?还有我怎么能用日期排序做#1?

4

1 回答 1

2

For chat organized into separate rooms or chat conversations, consider revising your structure to be the following:

/chat_messages/<room-id>/<message-id>/<message-data>

Using this structure, you can create a new room / conversation id by using a specific name of your choosing, or a Firebase-generated one using .push(). Whenever you want to write a new message to this room, do the following:

var chatMessagesRef = new Firebase('<YOUR-FIREBASE>.firebaseio.com/chat_messages');
function sendMessage(roomId, message) {
  chatMessagesRef.child(roomId).push(message);
}

Firebase essentially has two ways to query for data: by path and by priority (see Firebase Blog: Denormalizing Your Data is Normal for more information. Firebase push ids are automatically generated to sort chronologically, so you can fetch the n most recent messages for any conversation using a limit() query, such as:

chatMessagesRef.child(roomId).limit(20).on('child_added', function(snapshot) { ... });

Alternatively, you can fetch all messages for the conversation, automatically sorted chronologically, by removing the limit() query in the above statement.

If you haven't already, check out Firechat, which is Firebase's official open-source chat client, and includes a fully-documented JavaScript client, data structure, and security rules for chat.

于 2013-07-15T21:21:16.387 回答