我有这样的数据结构:
karmadots/events =
{
"event1": {
"categories" : ["fun"],
"name": "Some Title"
}
}
我希望能够附加到类别并使其具有 ["fun", "outside"]。我怎样才能做到这一点?当我更新事件路径上的子值时,整个类别路径都会重置。
编辑:
@IBAction func acceptUser(sender: AnyObject) {
// eventRef = karmadots/events (above)
var myRef = eventRef.childByAppendingPath("event1")
var eventDataOne = [
"categories":["fun"]
]
myRef.updateChildValues(eventDataOne)
// categories = ["fun"]
var eventDataTwo = [
//I want to be able to append to categories instead of overwriting
"categories":["outside"]
]
myRef.updateChildValues(eventDataTwo)
// categories = ["outside"] BUT I want it to be ["fun", "outside"]
}
我希望能够在第二次调用时附加到类别。
最佳答案
更新不是深度递归合并。从 API 文档中查看此简介以获取更新:
This will overwrite only children enumerated in the "value" parameter and will leave others untouched. Note that the update function is equivalent to calling set() on the named children; it does not recursively update children if they are objects. Passing null as a value for a child is equivalent to calling remove() on that child.
因此,要“更新”您的类别,您需要直接在这些类别而不是父类别上运行更新:
var myRef = eventRef.childByAppendingPath("event1/categories");
myRef.updateChildValues({"one": 1});
myRef.updateChildValues({"two": 2});
如前所述,您无法使用数组索引完成此类事件。我们怎么知道我们实际上正在“更新”哪个项目?如果另一个用户在数组中添加或删除一个项目,所有流畅的顺序键都会发生变化,我的更新现在不稳定且不可预测(请参阅我上面评论中的链接)。
相反,您可能想在这里做的是利用 childByAutoId
。这在保存数据指南中有所介绍。有一个 entire section dedicated to saving lists涵盖您在这里遇到的所有陷阱和正确的解决方案。
关于ios - 如何在 Firebase 中附加到带有其他对象的路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28536937/