How to query Firebase database object when criteria property is nested?

岁酱吖の 提交于 2020-01-03 03:06:26

问题


I have the following structure in Firebase database:

root
 - Users
 - Posts
   - -K_54s1smPPh6qN4znuT
     - key1: val
     - key2: val
     - User:
       - -K_54sSomeKeyFromUsersObject: "John Doe"
...

But I can't find any example in documentation how can I fetch all Posts by UserKey when I have structure like this.

I need help on how to make a query to compare nested data like this?


回答1:


One way to approach this is to save the reference to the posts on the user. Like this:

root
 - Users
   - [UserID]
      - UserPosts
        -K_54s1smPPh6qN4znuT
 - Posts
   - -K_54s1smPPh6qN4znuT
     - key1: val
     - key2: val
     - User:
       - -K_54sSomeKeyFromUsersObject: "John Doe"
...

So when you want to retrieve all posts by an user, you just look at the references on the user profile




回答2:


I would suggest an alternative

users
  uid_0
    name: "Frank"
  uid_1
    name: "Biff"

posts
  post_0
    msg: "some post"
    user_id: "uid_0"
  post_1
    msg: "Another post"
    user_id: "uid_1"

then a simple query will return all of uid_0's posts

let postsRef = root.child("posts")

postsRef.queryOrdered(byChild: "user_id").queryEqual(toValue: "uid_0")
        .observeSingleEvent(of: .value, with: { snapshot in
    print(snapshot)  //prints all of uid_0's posts
})

This avoids the need to gather up the post id's and then try to perform a SQL-like query WHERE Posts.ID in (k1, k2, k3...) as Firebase doesn't offer a query like that directly.

In response to a follow up comment about how to handle when a single post has multiple users...

posts
  post_0
    msg: "some post"
    users:
      uid_0: true
      uid_1: true
  post_1
    msg: "Another post"
    users:
      uid_1: true
      uid_2: true

The code to get the nodes that contain uid_1: true is similar and called a deep query or deep paths. That's an older post but will give you really good information.

let postsRef = root.child("posts")

postsRef.queryOrdered(byChild: "users/uid_1").queryEqual(toValue: true)
        .observeSingleEvent(of: .value, with: { snapshot in
    print(snapshot)  //prints all of uid_0's posts
})


来源:https://stackoverflow.com/questions/41428555/how-to-query-firebase-database-object-when-criteria-property-is-nested

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!