2017-04-26 65 views
0

鉴于以下结构,我如何才能检索特定用户通知?Firebase数据库:查询非规范化数据挣扎

即:uid0001 768,16能够检索列表:[xxxxx01, xxxxx02]

notifications 
    uid01 
    xxxxx01 
    uid02 
    xxxxx02 
    uid03 
    xxxxx03 
    uid04 
    xxxxx04 
users 
    uid0001 
    notifications 
     uid01 
     uid02 

不幸的是,这个怪物是极其低效:

firebase.database().ref(`users/${user.userId}/notifications`).once('value').then((snapshot) => { 
    snapshot.forEach((data) => { 
    firebase.database().ref(`notifications/${data.key}`).once('value').then((snap) => { 
     this.list.unshift(localUpdates) 
    }) 
    }) 
}) 

可能沿(警告,伪代码的东西线即将到来):

firebase.database().ref('notifications').on('child_added').equalTo('whatever the childs key is here').then((snapshot) => { 

}) 

As always任何方向,欢呼欢呼和腐烂的水果,谢谢!

回答

1

有一些sol sol;这里有两(原谅的伪代码,因为我不知道你的平台)

的确定方式

使用现有的结构,捕捉孩子节点/用户/ uid0001 /通知,然后遍历这些孩子,阅读通知中的孩子一次一个节点。

更好的方法

notifications 
    -yisijaoijsijdasd //generated by push() or childByAutoId() 
    for_user: "uid01" 
    notification: "Check this out" 
    timestamp: "20170421" 
    user_time: "uid01_20170421" //concatenated allows queries by > 1 item 
    -Y9s90kas9dkka9s 
    for_user: uid01 
    notification: "Yipee" 
    timestamp: "20170426" 
    user_time: "uid01_20170426" 

users 
    uid0001 

然后查询通知节点:

所有通知uid01

notificationsRef.queryOrdered(byChild: "for_user").equalTo("uid01") 

为uid01所有通知了持续4天

notificationsRef.queryOrdered(byChild: "user_time") 
       .startingAt("uid01_20170422") 
       .endingAt("uid01_20170426") 

你可以扩大本 - 例如,如果你想跟踪那些尚未被读取的通知,你可以添加

notifications 
    -yisijaoijsijdasd //generated by push() or childByAutoId() 
    for_user: "uid01" 
    notification: "Check this out" 
    timestamp: "20170421" 
    user_time: "uid01_20170421" 
    was_read: false 
    user_read: "uid01_false" 

和查询

notificationsRef.queryOrdered(byChild: "user_read").equalTo("uid01_false") 
+0

这件事我一直考虑。 'for_user'需要是一个数组。 'queryOrdered'仍然可以像任何工作吗?对于实例:'''queryOdered(byChild:“for_user”)。contains(“uid01”)''' – studiobrain

+1

@studiobrain号请不要在Firebase中使用或存储数组!参见[数组是邪恶的](https://firebase.googleblog.com/2014/04/best-practices-arrays-in-firebase.html)。对于我提出的结构,无论如何都没有理由使用数组。 Firebase中没有“包含”,这就是为什么我在我的解决方案中包含选项,以便您可以通过多种方式查询数据。 – Jay

+0

一致认为,这不仅仅意味着一个字面数组只是一个列表。上述将工作得很好,我只是深入一层,以获得基于用户的关联通知...谢谢! – studiobrain