我childByAutoId()
用来养育我的孩子。每个孩子看起来像:
{
user_id: 1
}
我想获取最近添加的最后10个,按时间DESC排序。最简单的方法是什么?
答案是,您需要使用一些逆逻辑,并且还将每个节点内的时间戳记键:值对存储为负值。我省略了user_id:1,以保持答案更干净。
这是Firebase的结构
"test" : {
"-KFUR91fso4dEKnm3RIF" : {
"timestamp" : -1.46081635550362E12
},
"-KFUR9YH5QSCTRWEzZLr" : {
"timestamp" : -1.460816357590991E12
},
"-KFURA4H60DbQ1MbrFC1" : {
"timestamp" : -1.460816359767055E12
},
"-KFURAh15i-sWD47RFka" : {
"timestamp" : -1.460816362311195E12
},
"-KFURBHuE7Z5ZvkY9mlS" : {
"timestamp" : -1.460816364735218E12
}
}
这就是将其写到Firebase的方式;我只是使用IBAction作为按钮来写出几个节点:
let testRef = self.myRootRef.childByAppendingPath("test")
let keyRef = testRef.childByAutoId()
let nodeRef = keyRef.childByAppendingPath("timestamp")
let t1 = Timestamp
nodeRef.setValue( 0 - t1) //note the negative value
以及读取它的代码
let ref = self.myRootRef.childByAppendingPath("test")
ref.queryOrderedByChild("timestamp").queryLimitedToFirst(3).observeEventType(.ChildAdded, withBlock: { snapshot in
print("The key: \(snapshot.key)") //the key
})
我声明了一个小函数来返回当前的时间戳
var Timestamp: NSTimeInterval {
return NSDate().timeIntervalSince1970 * 1000
}
和输出
The key: -KFURBHuE7Z5ZvkY9mlS
The key: -KFURAh15i-sWD47RFka
The key: -KFURA4H60DbQ1MbrFC1
如您所见,它们的顺序相反。
注意事项:
关于这一点,您也可以像往常一样读取数据并将其添加到Array中,然后对降序排列的数组进行排序。这会在客户端上花费更多的精力,如果您有10,000个节点,可能不是一个好的解决方案。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句