【问题标题】:How to update particular value of child in Firebase DB如何更新 Firebase DB 中子项的特定值
【发布时间】:2016-09-13 04:53:30
【问题描述】:

我正在关注这个document。以下是我的更新代码:

func updateDealResultToServer(key:String,dealResult : String)
{

    let post = ["dealResul": dealResult]
    let childUpdates =
        ["/komal_xyz/\(key)": post
        ]

    rootRef.updateChildValues(childUpdates)

}

这是我的 Firebase 数据库结构:

我只想更改dealResult 的值。每当我尝试为特定子节点(如1473670100726)运行上面的代码时,除dealResul 之外的其他值都会被删除。

【问题讨论】:

  • @omal Kamble:当我从一个设备的列表中删除值时,该值同时从另一台设备中删除?那是怎么发生的?请为android解释。我不明白如何工作?

标签: ios swift firebase firebase-realtime-database


【解决方案1】:

要更新 Firebase 实时数据库中特定节点的值,请使用:-

  • 您可以使用 runTransactionBlock:

      func updateTotalNoOfPost(completionBlock : (() -> Void)){
    
    
    let prntRef = FIRDatabase.database().reference().child("komal_kyz").child(your_AuroID).child("dealResul")
    
    prntRef.runTransactionBlock({ (resul) -> FIRTransactionResult in
        if let dealResul_Initial = resul.value as? Int{
    
            //resul.value = dealResul_Initial + 1
            //Or HowSoEver you want to update your dealResul. 
             return FIRTransactionResult.successWithValue(resul)
        }else{
    
            return FIRTransactionResult.successWithValue(resul)
    
        }
        }, andCompletionBlock: {(error,completion,snap) in
    
                print(error?.localizedDescription)
                print(completion)
                print(snap)
            if !completion {
    
               print("Couldn't Update the node")
            }else{
    
                completionBlock()
            }
        })
    
     }
    

    调用此函数时:-

    updateTotalNoOfPost{
           print("Updated")
          }
    
  • 或者只需致电updateValues

        let prntRef  = FIRDatabase.database().reference().child("komal_kyz").child(your_AuroID)
        prntRef.updateChildValues(["dealResul":dealResult]) 
    

PS:- 如果你只想增加一个特定的节点,最好使用 runTransactionBlock: 而不是 .updateChildValues。另请阅读:-https://stackoverflow.com/a/39458044/6297658

【讨论】:

    【解决方案2】:

    我建议使用setValue 进行单子更新(请记住,我使用的是 Swift 3,可能会应用轻微的语法更改,但您应该没问题):

    rootRef.child("komal_kyz").child(key).setValue(["dealResul":dealResult])
    

    【讨论】:

    • 使用setValue 是否更好?
    【解决方案3】:
    let ref = FIRDatabase.database().reference().root.child("users").child("childKey").updateChildValues(["childKeyForUpdate": "NewData"])
    

    【讨论】:

    • 您能详细说明一下吗?
    • 你能提供一些细节吗?
    • firebase 是一个数据库,用于在您的应用程序中实现聊天功能,firebase 提供套接字编程。如果您想更新任何选定的冷藏的值,那么此代码对您有帮助,其中“用户”是您在 firebaseDataBase 上的表名,“childKey”是用户表的冷藏,“childKeyForUpdate”是您选择的更新密钥并且“NewData”标识您的最新数据以替换旧
    猜你喜欢
    • 2017-03-28
    • 1970-01-01
    • 2018-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多