如何使用Swift为Firebase中的子项设置多个值?

时间:2022-09-08 21:26:10

I am trying to make a money related app which shows the user their spendings as a project to get used to Firebase. So I stumbled upon this issue; I can't seem to figure out how to add more than one expense assigned to a user. Whenever I add a new expense, the existing value in Firebase gets reset to the new value but I want it to store both the new and the old value. How can I do this?

我正在尝试制作与资金相关的应用程序,向用户展示他们作为一个习惯Firebase的项目。所以我偶然发现了这个问题;我似乎无法弄清楚如何添加分配给用户的多个费用。每当我添加新费用时,Firebase中的现有值都会重置为新值,但我希望它存储新值和旧值。我怎样才能做到这一点?

2 个解决方案

#1


1  

There's something called "autoID" if that helps. I'll link that in a few moments.

如果有帮助的话,有一种叫做“autoID”的东西。我会在一会儿之后把它联系起来。

Edit: It's used here.

编辑:它在这里使用。

#2


0  

childByAutoId() is what you want for swift. See Updating Or Deleting specific data section in the Read and Write Data on iOS

childByAutoId()是你想要的swift。请参阅iOS上的读写数据中的更新或删除特定数据部分

let thisUserRef = ref.child("users").child(users uid)
let expenseRef = thisUserRef.child("expenses").childByAutoId()
let dict = ["expense_type": "travel", "expense_amt": "1.99"]
expenseRef.setValue(dict)

will results in

将导致

users
  uid_0
    -Y88jn90skda //<- the node key created with childByAutoId
       expense_type: "travel"
       expense_amt: "1.99"

the childByAutoId is super powerful and allows 'random' node keys to be generated that contain your child data.

childByAutoId功能超强,允许生成包含子数据的“随机”节点密钥。

See the answer to this question and this other question for some tips on data modeling and queries.

有关数据建模和查询的一些提示,请参阅此问题的答案和此其他问题。

#1


1  

There's something called "autoID" if that helps. I'll link that in a few moments.

如果有帮助的话,有一种叫做“autoID”的东西。我会在一会儿之后把它联系起来。

Edit: It's used here.

编辑:它在这里使用。

#2


0  

childByAutoId() is what you want for swift. See Updating Or Deleting specific data section in the Read and Write Data on iOS

childByAutoId()是你想要的swift。请参阅iOS上的读写数据中的更新或删除特定数据部分

let thisUserRef = ref.child("users").child(users uid)
let expenseRef = thisUserRef.child("expenses").childByAutoId()
let dict = ["expense_type": "travel", "expense_amt": "1.99"]
expenseRef.setValue(dict)

will results in

将导致

users
  uid_0
    -Y88jn90skda //<- the node key created with childByAutoId
       expense_type: "travel"
       expense_amt: "1.99"

the childByAutoId is super powerful and allows 'random' node keys to be generated that contain your child data.

childByAutoId功能超强,允许生成包含子数据的“随机”节点密钥。

See the answer to this question and this other question for some tips on data modeling and queries.

有关数据建模和查询的一些提示,请参阅此问题的答案和此其他问题。