papay0
papay0

Reputation: 1311

Parse query multiple key swift in queryForTable()

I use Parse in order to manage my database.

I have a tableView with a searchBar. It's working very well.

My function about the query is the following :

override func queryForTable() -> PFQuery {
    var query = PFQuery(className: "students")
    if searchBar.text != "" {
        query.whereKey("prenom", containsString: searchBar.text.uppercaseString)
    }
    query.orderByAscending("prenom")
    return query
}

This works very well.

But now I want to add multiple key into my research, like :

query.whereKey("prenom", containsString: searchBar.text.uppercaseString)
query.whereKey("nom", containsString: searchBar.text.uppercaseString)

But this code, and it is normal, do : "I want searchBar.text IN prenom AND nom" And that's not what I want. I want to search for exemple : "John", and this result has to be "john" in "prenom" OR in "nom".

I don't know how to return a PFQuery with multiple keys into the query.

Does someone have an idea ?

Upvotes: 0

Views: 999

Answers (2)

papay0
papay0

Reputation: 1311

What I finally did is creat another column in my table and concatenate all my searchable information.

Then I do the same, I search my searchBar.text in this column, with containsString.

It works almost perfectly, the only issue I found is if I want to search in the reverse order of the string in my new column.

Upvotes: 0

rickerbh
rickerbh

Reputation: 9913

To do an OR query in Parse you need to use the Compound Query functionality. You construct two independent queries, then use the orQueryWithSubqueries method on PFQuery. For your example...

override func queryForTable() -> PFQuery {
  var query: PFQuery!
  if searchBar.text != "" {
    var prenomQuery = PFQuery(className: "students")
    var nomQuery = PFQuery(className: "students")
    prenomQuery.whereKey("prenom", containsString: searchBar.text.uppercaseString)
    nomQuery.whereKey("nom", containsString: searchBar.text.uppercaseString)
    query = PFQuery.orQueryWithSubqueries([prenomQuery, nomQuery])
  } else {
    query = PFQuery(className: "students")
  }
  query.orderByAscending("prenom")
  return query
}

I don't recall if the result set is uniqued (lets say someone has the search text in both their nom and prenom fields), so you should check that out.

Upvotes: 1

Related Questions