问题
I'm trying to do a sample application with firebase and I don't have quite understand how I should retrieve nested-flattered data.
Let's suppose I have a db like this
{
"users": {
"user-1": {
"email": "email1",
"matches": [
"match-1",
"match-2"
]
},
"user-2": {
"email": "email2",
"matches": [
"match-1",
"match-2"
]
},
"user-3": {
"email": "email3",
"matches": [
"match-2"
]
}
},
"matches": {
"match-1": {
"name": "Match 1",
"users": [
"user-1",
"user-2"
]
},
"match-2": {
"name": "Match 2",
"users": [
"user-1",
"user-2",
"user-3"
]
}
}
}
and I want to get all the match of the user-1. What I'm doing now is observe users.user-1.matches to get the matches list and then observe every match so the final flow is:
- observe users.user-1.matches
- observe matches.match-1
- observe matches.match-2
- ...
The question is: how can I optimize this flow? (like making something like the sql join)
My idea is to get something like this
{
"users": {
"user-1": {
"email": "email1",
"matches": {
"match-1": {
"name": "Match 1",
"users": [
"user-1",
"user-2"
]
},
"match-2": {
"name": "Match 2",
"users": [
"user-1",
"user-2",
"user-3"
]
}
}
}
}
}
So I can observer the whole structure at once.
I'm using firebase on iOS with swift but feel free to reply in every language you like.
Thanks.
回答1:
The answer linked in the comment is an answer, but let's simplify. Let's create a users node to store the users and a matches node to track the matches they played in.
Then we'll do a query to retrieve which matches user-1 played in:
users
user-1
name: "some name"
email: "somename@thing.com"
user-2
name: "another name"
email: "anothername@thing.com"
user-3
name: "cool name"
email: "coolname@thing.com"
and then the matches node
matches
match-1
name: "Match 1"
users
user-1: true
user-2: true
match-2
name: "Match 2"
users
user-1: true
user-2: true
user-3: true
match-3
name: "Match 3"
users
user-2: true
user-3: true
As you can see, we've structured the data to directly address our query
matchesRef.queryOrdered(byChild: "users/user-1").queryEqual(toValue: true)
.observe(.value, with: { snapshot in
print(snapshot)
});
and the snapshot will contain the nodes match-1 and match-2 but not match-3
来源:https://stackoverflow.com/questions/41015445/join-different-nodes-to-observe-them-at-once-with-firebase