Query data by value of deep child [duplicate]

家住魔仙堡 提交于 2019-12-25 09:05:26

问题


I have a data structure like this:

groups
  -KOrPKM2QUzuMnMlHfJu
    name: "Testgroup 1"
    members
      0: 123456789
      1: 987654321

  -KOrPKM2QUzuMnMFGfXa
    name: "Testgroup 2"
    members
      0: 123456789

The number of members is not defined. How can I get every group where one of the members is 123456789?

This question is different from this because in the other one the key of the value to check is actually known.


回答1:


The unique ID is generated when push is used, to retrieve the values under that node, you can use child_added.

firebase.database().ref('groups').on('child_added', snap => {
  firebase.database().ref('groups/'+snap.key+'/members').on('child_added', childSnapshot => {
    if(childSnapshot.val() == '123456789') {
      console.log('123456789 found in ' + snap.val().name);
    }
  });
});

The above code adds a child_added listener to groups so the moment it finds an existing child under groups or when a new child is added, it will trigger child_added, now snap.key contains what you want, the unique generated ID, to compare the value stored in members, another child_added listener is set on members which returns all the value stored under 0, 1...

Now childSnapshot.val() contains the value you want to compare, a simple IF statement is enough and if a match is found, you just print the group name with snap.val().name;




回答2:


I created NSObject class and called it FBNSArrayDB, inside it I created the firebase ID's in your case it will be:

   var name: NSString?
    var members: NSString?
    var 0: NSString?
var 1: NSString?

then do this in your UIViewController

var fbarray = [FBNSArrayDB]()//at the top

inside func

 let ref = FIRDatabase.database().reference().child(uid!)// I assume you are saving this under uid nod!



    ref.child("groups").observeEventType(.ChildAdded, withBlock: { (snapshot) in

        if let dictionary = snapshot.value as? [String: AnyObject]{
            let xy = FBNSArrayDB()
            xy.setValuesForKeysWithDictionary(dictionary)

            guard let SomeV = xy.0

                    else {
                        print ("NA")
                        return
                }

                if SomeV == "123456789"
{
self.fbarray.append(xy) //this way you can use the array values outside the Func

print (xy.name)
print (xy.0)
print (xy.1)
print (snapshot.key) // if you want to get the AutoID 



 }


        }
        }, withCancelBlock: nil)


来源:https://stackoverflow.com/questions/38886387/query-data-by-value-of-deep-child

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!