获取随机的Firebase数据库条目 [英] Get random firebase database entry
问题描述
users
--45jklj4kljfejlk34 // random uid
---- id:1 //我在创建用户的时候手动添加这个(也许它有助于获得一个随机的用户)
---- someData:true
--454jkljkljefnd4lk
---- id:2
---- someData:true
I想要得到一个随机的用户,但我不知道如何。
我试过了。如下所示:
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $' ))+ 1
let userRef = DataService.sharedInstance.DB_REF_USERS.queryOrdered(byChild:id)。queryStarting(atValue:rand).queryLimited(toFirst:1))
我从数据库中获得usersCount。在那里,我增加了数字,每次我添加一个用户。
但这不起作用。这是我得到,如果我打印此:
(/ users {
i = id;
l = 1;
sp = 1;
vf = l;
})
任何建议,我怎么能做到这一点?
当我创建一个用户,我将他添加到用户树。另外,我把他添加到一个numUsers树(我选择名字很糟糕,对不起)。看起来像这样:
users
--45jklj4kljfejlk34 // random uid
---- id :1
---- someData:true
--454jkljkljefnd4lk
---- id:2
---- someData:true
numUsers
--1:45jklj4kljfejlk34
--2:454jkljkljefnd4lk
numUsers由 id
作为键和 uid
作为值组成。每当我添加一个新用户,我抓住usersCount(我以前增加1),并用它作为关键。
这样,我可以轻松地抓住一个随机的用户使用这个:
$ $ $ $ $ $ $ DataService.sharedInstance.DB_REF_USERS.child(\(rand))。observeSingleEvent( :.value,其中:{(snapshot)in print(snapshot)})
I've got users like this inside my database:
users
--45jklj4kljfejlk34 // random uid
----id: 1 // I add this manually when creating a user (maybe it helps getting a random user)
----someData: true
--454jkljkljefnd4lk
----id: 2
----someData: true
I want to get a random user, but I don't know how. I tried sth. like this:
let usersCount = DataService.sharedInstance.DB_USER_COUNT
let rand = Double(arc4random_uniform(UInt32(usersCount))) + 1
let userRef = DataService.sharedInstance.DB_REF_USERS.queryOrdered(byChild: "id").queryStarting(atValue: rand).queryLimited(toFirst: 1))
I get usersCount from the database. There, I increment the figure every time I add a user.
But this doesn't work. This is what I get if I printed this:
(/users {
i = id;
l = 1;
sp = 1;
vf = l;
})
Any suggestions, how I can achieve this?
So, as firebase works quite differently than relational based databases, redundancies seem acceptable in order to be fast and efficient. So I came up with a workaround that works for me.
When I create a user I add him to the "users" tree. Additionally, I add him to a "numUsers" tree (I'm terrible at choosing names, sorry for that). This looks like that:
users
--45jklj4kljfejlk34 // random uid
----id: 1
----someData: true
--454jkljkljefnd4lk
----id: 2
----someData: true
numUsers
--1: 45jklj4kljfejlk34
--2: 454jkljkljefnd4lk
So, "numUsers" consists of an id
as key and the uid
as value. Every time I add a new user, I grab the "usersCount" (which I incremented by 1 before) and use it as key.
This way, I can easily grab a random user by using this:
DataService.sharedInstance.DB_REF_USERS.child("\(rand)").observeSingleEvent(of: .value, with: {(snapshot) in print(snapshot) })
这篇关于获取随机的Firebase数据库条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!