Filter and sort on multiple values with Firebase

前端 未结 1 726
故里飘歌
故里飘歌 2020-12-07 23:35

I\'m building a social app using Firebase. I store posts in Firebase like this:

posts: {
   \"postid\": {
      author: \"userid\" 
      text: \"\",
      d         


        
相关标签:
1条回答
  • 2020-12-08 00:24

    You can use only one ordering function with Firebase database queries, but proper data structure will allow you to query by multiple fields.

    In your case you want to order by category. Rather than have category as a property, it can act as an index under posts:

    posts: {
       "categoryid": {
           "postid": {
             author: "userid" 
             text: "",
             date: "timestamp",
             category: "categoryid",
             likes: 23
           }
       }
    }
    

    Now you can write a query to get all the posts underneath a specific category.

    let postsRef = Firebase(url: "<my-firebase-app>/posts")
    let categoryId = "my-category"
    let categoryRef = postsRef.childByAppendingPath(categoryId)
    let query = categoryRef.queryOrderedByChild("date")
    query.observeEventType(.ChildAdded) { (snap: FDataSnapshot!) {
      print(snap.value)
    }
    

    The code above creates a reference for posts by a specific category, and orders by the date. The multiple querying is possible by the data structure. The callback closure fires off for each individual item underneath the specified category.

    If you want to query further, you'll have to do a client-side filtering of the data.

    0 讨论(0)
提交回复
热议问题