How to properly structure Firebase database to allow easy reading and removal

后端 未结 1 1650
故里飘歌
故里飘歌 2020-12-06 15:17

I am creating a recipe finding app and basically I have a \"favorites\" where if the user favorites a recipe, they will be able to easily access it in the favorites tab of t

相关标签:
1条回答
  • 2020-12-06 15:45

    You might wanna consider making favourites as a NSDictionary:-

     app:
      users:
       2ReAGRZlYiV5F2piwMakz59XDzl1: //(uid)
        favorites:
          {172171 : true,
            4123123 : true,..} 
    
    • For Appending in the favourites:-

        USERS_REF.child(uid).child("favorites").updateChildValues([recipeID: "true"]) 
      

      Mind that , if your recipeID is unique, i.e doesnt already exist at favourites node Only then it will append the value, if the recipieID already exists it will just update its value (Dont prefer this for appending, look up the next option)

      Or

      let prntRef = USERS_REF.child(uid).child("favorites")
      prntRef.observeSingleEventOfType(.Value, withBlock: { (snap) in
      
          if let favDict = snap.value as? NSMutableDictionary{
              favDict.setObject("true",forKey : recipeID)
              prntRef.setValue(favDict) 
          } else {
              prntRef.setValue(["true":recipeID])
          }
      })
      
    • For Updating in the favourites:-

       USERS_REF.child(uid).child("favorites").updateChildValues([recipeID: "false"])  //User doesn't like's the recipe anymore
      
    • For Deleting from the favourites:-

       USERS_REF.child(uid).child("favorites").child(recipeID).removeValue()  //User want to remove this item from its history
      
    • Whilst Retrieving

       let prntRef = USERS_REF.child(uid).child("favorites")
       prntRef.observeSingleEventOfType(.Value, withBlock: {(snap) in
      
           if let favDict = snap.value as? [String:AnyObject]{
      
               for each in favDict{
      
                   let eachRecipeId = each.0 //recipeID
                   let isMyFav = each.1 // Bool
               }
      
           } else {
               print("No favourites")
           }
      })
      
    • Whilst Retrieving For a known key-value pair

       let prntRef = USERS_REFFIR.child("users").queryOrderedByChild("favorites/\(recipeID)").queryEqualToValue(true)
       prntRef.observeSingleEventOfType(.Value, withBlock: {(snap) in
      
           //snap containing all the Users that carry that recipeID in their favourite section 
       })
      
    0 讨论(0)
提交回复
热议问题