NoSQL中的总菜单将我的手放在Firebase数据库上,当我需要将过滤器应用到我的数据库时会弹出一些问题。
我的结构类似于:
{
"burgers": {
"burg-one": {
"name": " Burger One"
},
"burg-two": {
"name": " Burger Two"
}
},
"ingredients": {
"bacon": {
"name": "Bacon",
"burgers": {
"burg-one": true,
"burg-two": true
}
},
"fried-egg": {
"name": "Fried Egg",
"burgers": {
"burg-two": true
}
}
}
}
我正试图过滤burg-one
所有的成分。在Java中,我尝试了下面的代码,但没有成功:
firebaseDatabase()
.child("ingredients")
.orderByChild("burgers")
.equalTo("bacon")
.addListenerForSingleValueEvent(...);
我在这里已经阅读了几个类似问题的答案,但我无法理解我应该在这里做些什么。
建模这些关系的正确方法是否必须复制两个模型中彼此相关的列表?在这种情况下,我的Burger
模型如此:
{
"burgers": {
"burg-one": {
"name": " Burger One",
"ingredients": {
"bacon": true,
}
}
}
这样我就必须查询ingredients
中的每个元素来获取它的数据?
对这些问题的任何解释都将不胜感激。
答案 0 :(得分:0)
所以我最终改变了我的结构并需要添加另一系列请求以获得汉堡的成分列表。结果如下:
{
"burgers": {
"burg-one": {
"name": " Burger One",
"ingredients": {
"bacon": true,
}
},
"burg-two": {
"name": " Burger Two",
"ingredients": {
"bacon": true,
"fried-egg": true
}
}
},
"ingredients": {
"bacon": {
"name": "Bacon",
"burgers": {
"burg-one": true,
"burg-two": true
}
},
"fried-egg": {
"name": "Fried Egg",
"burgers": {
"burg-two": true
}
}
}
}
使用该数据库,我必须在代码中进行以下更改:
// Query database to get all burgers and receive in a single value listener
firebaseDatabase()
.child("ingredients")
.orderByChild("burgers")
.equalTo("bacon")
.addListenerForSingleValueEvent(burgersValueEventListener);
// Add received burgers to a list in the database listener
burgersValueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
burgerList.add(child.getValue(Burger.class));
}
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
Burger burger = burgerList.get(0); // Get a burger to query its ingredients
// Retrieve the burger's ingredient list and query the database for each one it has with a listener
for (String ingredient : burger.ingredients.keySet()) {
firebaseDatabase
.child("ingredients")
.orderByKey()
.equalTo(ingredient)
.addListenerForSingleValueEvent(ingredientValueEventListener);
}
// Receive each (separately) ingredient's details in the listener
ingredientValueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
Ingredient burger = child.getValue(Ingredient.class); // Do something with your ingredient
}
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
这很好但我希望我们有一种更简单的方法来实现过滤,但我理解NoSQL数据库模型的工作原理。