Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase queryEqualToValue with childKey

I am trying to query data in my Firebase database using:

queryEqual(toValue: Any?, childKey: String?)

My database structure:

Schools {
    testUID1 {
        schoolNameLC: test school 1
    }
}

My query is:

databaseReference.child("Schools").queryEqual(toValue: "test school 1", childKey: "schoolNameLC").observe(.value) { (snap) in
        print(snap)
    }

This query prints out null and I can't quite get it to work. Because of the way my app is set up, I don't know that the key schoolNameLC has a value testSchool1 under the parent key of testUID1. All I want to do is search through the Schools in my database and return anything with a schoolNameLC value of test school 1.

like image 616
Dan Levy Avatar asked Jan 02 '17 04:01

Dan Levy


People also ask

What is getKey () in firebase?

getKey() returns the key (last part of the path) of the location of the Snapshot. getReference() returns the Reference for the location that generated this Snapshot. getValue() returns the data contained in this Snapshot. hasChild() returns true if the specified child path has (non-null) data.

Is firebase relational database or not?

The key differences between Firebase and MySQL: Architecture: Firebase is a NoSQL database that stores and syncs data in real-time (a real-time document store); MySQL is an open-source relational database management system based on the domain-specific language SQL.

Is firebase a JSON database?

All Firebase Realtime Database data is stored as JSON objects. You can think of the database as a cloud-hosted JSON tree. Unlike a SQL database, there are no tables or records. When you add data to the JSON tree, it becomes a node in the existing JSON structure with an associated key.


1 Answers

The two-parameter queryEqualToValue:childKey: (and its brethren queryStartingAtValue:childKey: and queryEndingAtValue:childKey:) are unfortunately some of the most misunderstood methods in the Firebase Database API.

To order by a child and then filter on a value of that child, you have to call queryOrderedByChild().queryEqualToValue(). So as @ElCaptainV2.0 said:

databaseReference.child("Schools")
    .queryOrderedByChild("scho‌​olNameLC")
    .queryEqua‌​lToValue("test school 1")

You only should use the childKey: parameter if you also want to start at a specific key in all nodes that have the same matching test school 1 value. This overload is really mostly useful when you're trying to paginate/endless scroll results.

like image 151
Frank van Puffelen Avatar answered Oct 03 '22 15:10

Frank van Puffelen