Complex query from Firebase

你离开我真会死。 提交于 2019-12-25 08:27:23

问题


I need to join my two tables from Firebase. Right now, i got the data structure as shown below.

When a log is created by a user, it gets a unique ID from Firebase. This ID is saved under the user who created it (test2@test.dk).

But i want to show the logs, only to the user who is logged in, how do i achieve this? Right now, i can only get the key, but i need the data such as duration and startDate.

logs
  -KVMbJKN1i2vAxzutiYq
    duration: 14
    startDate: 28/10/2016

  -KVMbLL4i_9dwaRZ9REB
    duration: 28
    startDate: 01/09/2016

  -KVMiLwoSY34TZpf8mST
    duration: 14
    startDate: 2/2/2016

users
  Edl7nDpJWIdNmDVUDn87p31d9mN2
    email: test@test.dk
    firstName: test
    imageUrl: URL
    lastName: test
    provider: Facebook

  KX6DRd0k5fasEaqB8vJWiXkp69L2
    email: test1@test.dk
    firstName: test1
    imageUrl: URL
    lastName: test1
    provider: Firebase

  WRgxyjSpQlUPmeJwfF9I7PhpvHs1
    email: test2@test.dk
    firstName: test2
    imageUrl: URL
    lastName: test2
    logs
      -KVMbJKN1i2vAxzutiYq: true
      -KVMbLL4i_9dwaRZ9REB: true
      -KVMiLwoSY34TZpf8mST: true
     provider: Firebase

回答1:


To get the duration startDate , just query it to the desired location of the specific node:-

FIRDatabase.database().reference().child("user/\(FIRAuth.auth()!.currentUser!.uid)/logs").observeSingleEvent(of: .value, with: {(userSnap) in 

 if let SnapDict = userSnap.value as? [String:AnyObject]{

 for each in SnapDict{ 

  FIRDatabase.database().reference().child("logs/\(each.key)").observeSingleEvent(of: .value , with : {(Snap) in 

     print(Snap.value)   

   })
  }
  }
})



回答2:


Just add a child to each log node that identifies which user owns it. So each will have duration, startDate and uid.

logs
  -KVMbJKN1i2vAxzutiYq
    duration: 14
    startDate: 28/10/2016
    uid: WRgxyjSpQlUPmeJwfF9I7PhpvHs1

That way the log node points to the user that owns it and users/logs node identifies the logs for that user.

From there, just a query for logs where uid = the logged in uid will return the log nodes and child data you need in a snapshot.



来源:https://stackoverflow.com/questions/40346907/complex-query-from-firebase

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