简体   繁体   中英

Complex query from Firebase

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

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)   

   })
  }
  }
})

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM