我想使用 .indexOn: timestamp 从关注的用户那里获取最新的帖子(我正在使用 UTC 时间来做到这一点)但我不知道如何同时过滤按时间戳排序的关注帖子以便能够使用limitToLast 在这种情况下正确吗?
posts
post_id_0
timestamp: _
ownerID: user_id_0
...
users
user_id_0
following
user_id_0: true
user_id_1: true
followers
user_id_x: true
user_id_y: true
...
最佳答案
如果您想按时间戳排序并将其限制为最后一个(这将是最近的)
let postsRef = self.myRootRef.childByAppendingPath("posts")
postsRef.queryOrderedByChild("timestamp").queryLimitedToLast(1)
.observeSingleEventOfType(.Value, withBlock: { snapshot in
if ( snapshot.value is NSNull ) {
print("not found")
} else {
for child in snapshot.children {
let q = child.value["ownerID"] as! String
print(q)
}
}
})
如果我理解这个问题,您还想将帖子限制为特定用户。换句话说,您想获取 user_0 创建的最新帖子。 (即查询:where xx && yy)
有几种方法可以做到这一点
1) 跟踪那些在用户节点内的帖子
users
user_id_0
following
xxxx
followers
yyyy
3_most_recent_posts
post_id_3: true
post_id_2: true
post_id_1: true
然后您可以直接获取特定的帖子。
2) 第二种选择是格式化您的 Firebase 以匹配您想要获得的内容:
posts
post_id_0
owner_timestamp: user_id_0_20160611081433
然后,查询 posts 节点以获取从 user_id_0_ 开始并将其限制为最后一个 x 的值
postsRef.queryOrderedByChild("owner_timestamp")
.queryStartingAtValue("user_id_0_")
.queryLimitedToLast(1)
.observeSingleEventOfType(.Value, withBlock: { snapshot in
if ( snapshot.value is NSNull ) {
print("not found")
} else {
for child in snapshot.children {
let q = child.value["ownerID"] as! String
print(q)
}
}
})
关于ios - Swift - 如何在 Firebase 中创建(全部)关注用户?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37753536/