在火力地堡保存键值的字典使用雨燕
问题描述:
这个问题是一个跟进来自: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上。但我希望能够采取措施,保存配料的全部配方。大多数例子给出了一组具有声明属性的字典。然而,我的配方可以是随机的,因为每个配方可以有随机数量的配料
答
在你addRecipe
功能,试试这个:
...
let ingredients: [String] = ...
var ingredientsJSON = [String: Bool]()
for key in ingredients {
ingredientsJSON[key] = true
}
let recipeJSON: [String : Any] = [
"recipeName" : itemNameText,
"recipeID" : recipeKey,
"ingredients": ingredientsJSON
]
let recipe = ["\(recipeKey)" : recipeJSON]
databaseRef.child("RecipeData").child("recipe").updateChildValues(recipe)
...
要存储成分与配方一起
,在一去,对不对?在此查询中,databaseRef.child(“RecipeData”)。child(“recipe”)。updateChildValues(recipe) –
正确,此时只存储配方。我不知道如何储存食材。 – Chace
是否在Firebase上已有“IngredientData”:{ “ingredients”:{__data__}}? –