当child是列表时按子查询和过滤

时间:2018-11-29 08:35:54

标签: swift firebase firebase-realtime-database

我在弄清楚数据是列表时如何进行筛选和查询时遇到了一些麻烦。在当前的数据库模型中,我进行对话,然后在每个UID下是该对话的参与者。我希望能够查找特定用户所属的所有对话。

database model

我不确定在没有真正的“孩子”的情况下如何编写代码

void networkUsage() {
    // Get running processes
    ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    List<ActivityManager.RunningAppProcessInfo> runningApps = manager.getRunningAppProcesses();
    for (ActivityManager.RunningAppProcessInfo runningApp : runningApps) {
        long received = TrafficStats.getUidRxBytes(runningApp.uid);
        long sent = TrafficStats.getUidTxBytes(runningApp.uid);
        Log.d(LOG_TAG, String.format(Locale.getDefault(), 
                "uid: %1d - name: %s: Sent = %1d, Rcvd = %1d", runningApp.uid, runningApp.processName, sent, received));
    }
}

1 个答案:

答案 0 :(得分:1)

由于Firebase查询的局限性,您将需要在数据库中创建一个新集合,以跟踪用户所属的所有对话。它的结构应如下所示:

usersConversations {
    userID1 {
        conversationID1: timestamp (or what ever value you would like, I would recommend a timestamp they joined so you can query the latest conversations, etc.)
        conversationID2: timestamp 
        conversationID3: timestamp
    userID2 {
        conversationID1: timestamp
        conversationID2: timestamp
    } ... and so on
}

每当用户加入或退出对话以及您现有的conversations集合时,您都需要添加和删除此集合。

您可以通过执行以下操作来获得用户与uid userID的所有对话:

databaseRef.child("usersConversations").child(userID).observeSingleEvent(of: .value) (snapshot) in {
    if snapshot.exists() {
         // each snapshot child's key will be a conversationID that they are a part of 

    } else {
         // the user is part of no conversations
    }

}