Firebase Queryequaltovalue with Childkey

Firebase queryEqualToValue with childKey

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.

queryEqual(toValue: true, childKey: isFromCreator) not working?

The second argument to queryEqual(toValue:) is not the key on which to filter, but the so-called disambiguation key. So if there are multiple node matching the value, the database finds the one whose key is equal to childKey and starts returning nodes from there.

So if you want to filter on isFromCreator, you will need:

ref.child("ClubContent").child("jhTFin5npXeOv2fdwHBrTxTdWIi2").child("1622325513718")
.queryOrdered(byChild: "isFromCreator")
.queryEqual(toValue: true)

Then if there are multiple child nodes with isFromCreator equal to true, you can determine which one to start returning nodes from by passing its key as an extra value in to .queryEqual(toValue:), for example:

    .queryEqual(toValue: true, childKey: "-Lasdnsa39132...")

It seems you're trying to sort/filter on two properties, which is not possible in the Realtime Database. Firebase Database queries can only order/filter on a single property.

In many cases it is possible to combine the values you want to filter on into a single (synthetic) property. You could for example have a property: "isFromCreator_timestamp": "true_128348712" and order/filter on that.

For another example of this and other approaches, see my answer here: Query based on multiple where clauses in Firebase

How can I retrieve data with queryEqualToValue in auto id child. Firebase-iOS

Given your realtime database looks something like this:

{
"students": {
1: {
"name": {
"first_name": "Nathapong",
"nick_name": "Oniikal3"
}
}
}
}

You can observe the students path with the event type ChildAdded and order the query by child key name/first_name. Then you can use queryEqualToValue to find students with a particular first name.

let ref = FIRDatabase.database().referenceWithPath('students').queryOrderByChild("name/first_name").queryEqualToValue("Nathapong")

ref.observeSingleEventOfType(.ChildAdded, block: { snapshot in
print(snapshot)
})


Related Topics



Leave a reply



Submit