Firebase 查询排序无法正常工作 [英] Firebase query ordering not working properly
问题描述
基本上我过去一周一直在使用 Firebase,最近我偶然发现了queryOrderedByChild()",据我所知 - 允许您对 Firebase 中的数据进行排序.但是,我似乎没有得到正确的结果.我的 Firebase 数据如下所示:
Basically I have played with Firebase for the past week, and I recently stumbled upon the 'queryOrderedByChild()' that as far as I know - allows you to sort data in firebase. However, I seem to not get the proper results. My Firebase data looks like this:
{
"names" : {
"-KHVUwXdVPHmrO_O5kil" : {
"id" : "0",
"name" : "Jeff"
},
"-KHVV7lCeac0cZNMi9fq" : {
"id" : "3",
"name" : "Stig"
},
"-KHVVCjXgl0XxasVOHF1" : {
"id" : "13",
"name" : "Ali"
},
"-KHVVJtyUO-yJZiompJO" : {
"id" : "7",
"name" : "Hannah"
},
"-KHVVR8tMSO1Oh7R8tR1" : {
"id" : "2",
"name" : "Amanda"
}
}
}
,我的代码是这样的:
ref.childByAppendingPath("names")
.queryOrderedByChild("id")
.observeEventType(.ChildAdded) { (snapshot:FDataSnapshot!) in
if let myID = snapshot.value["id"] as? String {
print(myID)
}
输出仍然是随机顺序,显示:0, 2,7,1,8,4 - 这不应该是数字吗?我究竟做错了什么?我怎样才能对它进行排序,使它得到升序或降序的数字?
The output is still in a random order, displaying: 0, 2,7,1,8,4 - Isn't this supposed to be numeric? What am I doing wrong? How can I sort it so it get's numeric either ascending or descending?
推荐答案
您说您是按数字排序,但您的 id
属性值存储为字符串.
You say that you're ordering by a number, but the value of your id
property is stored as a string.
由于您将它们存储为字符串,它们将按词典顺序返回.
Since you're storing them as a string, they will be returned in lexicographical order.
如果您希望它们按数字顺序排列,则应将它们存储为数字
If you want them to be in numerical order, you should store them as numbers
"-KHVUwXdVPHmrO_O5kil" : {
"id" : 0,
"name" : "Jeff"
},
或者,您可以将 id 存储为以零填充的字符串:
Alternatively, you could store the ids as zero-padded strings:
{
"names" : {
"-KHVUwXdVPHmrO_O5kil" : {
"id" : "0000",
"name" : "Jeff"
},
"-KHVV7lCeac0cZNMi9fq" : {
"id" : "0003",
"name" : "Stig"
},
"-KHVVCjXgl0XxasVOHF1" : {
"id" : "0013",
"name" : "Ali"
},
"-KHVVJtyUO-yJZiompJO" : {
"id" : "0007",
"name" : "Hannah"
},
"-KHVVR8tMSO1Oh7R8tR1" : {
"id" : "0002",
"name" : "Amanda"
}
}
}
由于字符串的长度都相同,它们将按正确的顺序排序.但是你必须决定后一种解决方案中字符串/最大id值的长度,所以看起来更糟.
Since the strings are all the same length, they will be sorted in the correct order. But you'll have to decide on the length of the string/maximum id value in the latter solution, so it seems worse.
这篇关于Firebase 查询排序无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!