如何查询Firebase数据childByAutoID? [英] How to query firebase data childByAutoID?
问题描述
可以仅一遍查询此路径并按locality
值(例如伦敦)对商品进行排序,但仅获取以某个
Is is possible to query this path in only one go and order the items by locality
value (e.g London), but get only the items which are starting/ending at a certain childByAutoID
?
原因-当我在tableView中向下滚动时,我想从数据库中获取按某个区域排序的更多旧项目,例如伦敦,并且旧于oldestKey
,这是媒体的关键物品.
Reason - when I scroll down in a tableView, I want to get from database more older items ordered by a certain area, e.g London and older than oldestKey
which is the key of the media item.
最初使用.childAdded
方法下载第一批项目.
The first batch of items is downloaded initially using .childAdded
method.
数据:
media
-LgSsaqYzevONPTk2447 // <- childByAutoID
caption: "12"
locality: "City of London"
mediaUID: "-LgSsaqYzevONPTk2447"
-LgSsZnpSNLJwZBNgXGJ
caption: "15"
locality: "New York"
mediaUID: "-LgSsZnpSNLJwZBNgXGJ"
代码
class func observeNewMediaSingleTime(_ oldestKey: String,_
userLocality: String, _ completion: @escaping ([Media], String?) -> Void) {
let ref = Database.database().reference()
let query = ref.child("media").queryOrdered(byChild: userLocality).queryStarting(atValue: oldestKey).queryLimited(toLast: 50)
ref.observeSingleEvent(of: .value, with: { snapshot in
guard snapshot.exists() else {
completion([],nil)
return}
let firstItem = snapshot.children.allObjects.first as! DataSnapshot
var arrayOfMedia = [Media]()
var count = 0
let enumerator = snapshot.children
while let mediaItem = enumerator.nextObject() as? DataSnapshot {
let media = Media(dictionary: mediaItem.value as! [String:Any])
print("media.locality is \(media.locality)")
//check if new media has same key as oldest post downloaded in previously
if media.mediaUID != oldestKey{
count += 1
arrayOfMedia.append(media)
}
}//end of while
arrayOfMedia.reverse()
if count == arrayOfMedia.count {
let updatedOldestKey = firstItem.key
completion(arrayOfMedia, updatedOldestKey)
}
})
}
推荐答案
If you know the locality
value of the first item, this is possible with queryStarting(atValue:childKey:)
:
let query = ref.child("media")
.queryOrdered(byChild: "locality")
.queryStarting(atValue: "City of London", childKey: "-LgSsaqYzevONPTk2447")
.queryLimited(toLast: 50)
因此,以上代码按其子节点的位置对所有子节点进行排序,然后开始使用locality
= "City of London"
和键-LgSsaqYzevONPTk2447
从处返回结果.
So the above orders all child nodes by their locality, and then starts returning results at the with with locality
="City of London"
and key -LgSsaqYzevONPTk2447
.
这篇关于如何查询Firebase数据childByAutoID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!