Reputation: 561
I am trying to create multiple children inside a child. I can currently create this inside my recipe:
{
"RecipeData": {
"recipe": {
"-KjTSH4uPQ152Cr-hDok": {
"name": "Cook rice",
"ID": "-KjTSH4uPQ152Cr-hDok",
}
}
}
}
Using:
let recipe: [String : Any] = ["name" : self.recipe.name,
"ID" : self.recipe.key]
The class of the recipe looks like this:
class Recipe {
var name: String!
var key: String
init(from snapshot: FIRDataSnapshot) {
let snapshotValue = snapshot.value as! [String: Any]
self.name = snapshotValue["name"] as! String
self.key = snapshot.key
}
}
But I now want to create another array of children which would be inside "method" and look something like this.
{
"RecipeData": {
"recipe": {
"-KjTSH4uPQ152Cr-hDok": {
"name": "Cook rice",
"ID": "-KjTSH4uPQ152Cr-hDok",
"method": [
{
"step 1": "instruction 1"
},
{
"step 2": "instruction 2"
},
{
"step 3": "instruction 3"
}
]
}
}
}
}
Edit:
The recipe is updated this way
databaseRef.child("RecipeData").child("recipe").updateChildValues(recipe)
I have looked at Firebase How to update multiple children? which is written in javascript, but not sure how to implement it. Feel free to let me know if there are better questions or examples out there.
Upvotes: 2
Views: 2556
Reputation: 7668
You can create multiple children inside of a node just as you have been doing with the "recipe"
node. For example:
{
"RecipeData": {
"recipe": {
"-KjTSH4uPQ152Cr-hDok": {
"name": "Cook rice",
"ID": "-KjTSH4uPQ152Cr-hDok",
"method": {
"Step1":"instruction1",
"Step2":"instruction2",
"Step3":"instruction3"
}
}
}
}
This is better practice as you can look up each step by key. Although, as Firebase Database keys are strings ordered lexicographically, it would be better practice to use .childByAutoId()
for each step, to ensure all the steps come in order and are unique. I'll just keep using "stepn" for this example though.
If you needed further information inside each step, just make one of the step keys a parent node again:
{
"RecipeData": {
"recipe": {
"-KjTSH4uPQ152Cr-hDok": {
"name": "Cook rice",
"ID": "-KjTSH4uPQ152Cr-hDok",
"method": {
"Step1": {
"SpatulaRequired" : true,
"Temp" : 400
}
}
}
}
}
This can be achieved by by calling .set()
on a Dictionary of Dictionaries. For example:
let dict: [String:AnyObject] = ["Method":
["Step1":
["SpatulaRequired":true,
"temp":400],
["Step2":
["SpatulaRequired":false,
"temp":500]
]]
myDatabaseReference.set(dict)
Upvotes: 4