這個問題是一個跟進來自:Post Array to firebase Database in Swift在火力地堡保存鍵值的字典使用雨燕
我想一些ingredients
保存到一個recipe
以後能夠檢索與裏面的成分在整個配方它。看了上面的問題和這篇博文https://firebase.googleblog.com/2014/04/best-practices-arrays-in-firebase.html。我能夠重新構造我的數據庫
這是我的成分辭典:
{
"IngredientDict": {
"-KkbWdomTYdpgEDLjC9w": "Eggs",
"-KkbWvaa5DT1PY7q7jIs": "Spaghetti",
"-KkbaDQ8wYJxR3O2OwKd": "Parmesan"
// More possible ingredients
}
}
這是我的成分的資料:
{
"IngredientData": {
"ingredients": {
"-KkbWdomTYdpgEDLjC9w": {
"name": "Eggs",
"uid": "-KkbWdomTYdpgEDLjC9w"
},
"-KkbWvaa5DT1PY7q7jIs": {
"name": "Spaghetti",
"uid": "-KkbWvaa5DT1PY7q7jIs"
},
"-KkbaDQ8wYJxR3O2OwKd": {
"name": "Parmesan",
"uid": "-KkY90e7dAgefc8zH3_F"
// More possible ingredients
}
}
}
}
我現在想這些組的成分添加到我的配方在一個行動。這是我目前如何製作料理:
@IBAction func addRecipe(_ sender: Any) {
guard let itemNameText = recipeName.text else { return }
guard itemNameText.characters.count > 0 else {
print("Complete all fields")
return
}
let recipeKey = databaseRef.child("RecipeData").child("recipe").childByAutoId().key
let recipeItem: [String : Any] = ["recipeName" : itemNameText, "recipeID" : recipeKey]
let recipe = ["\(recipeKey)" : recipeItem]
databaseRef.child("RecipeData").child("recipe").updateChildValues(recipe)
print("\(itemNameText) was added")
}
這是結果:
{
"RecipeData": {
"recipe": {
"-Kkv36b_aPl7HAO_VYaJ": {
"recipeName": "Spaghetti Carbonara",
"recipeID": "-Kkv36b_aPl7HAO_VYaJ"
}
}
}
}
如何添加的成分?目前,我可以手動將其添加到Firebase上。但我希望能夠採取措施,保存配料的全部配方。大多數例子給出了一組具有聲明屬性的字典。然而,我的配方可以是隨機的,因爲每個配方可以有隨機數量的配料
,在一去,對不對?在此查詢中,databaseRef.child(「RecipeData」)。child(「recipe」)。updateChildValues(recipe) –
正確,此時只存儲配方。我不知道如何儲存食材。 – Chace
是否在Firebase上已有「IngredientData」:{ 「ingredients」:{__data__}}? –