Search code examples
joinparse-platformnosql

Parse Server - How to lookup and replace a field of a query with field from another table in a single query


I could not find a solution on Parse Server for the below issue. It is equivalent to using JOIN in SQL but because Parse Server uses NoSQL, the solution is not join.

Issue ; Reporting screen displays results of a query. But one of the field needs to be looked up from another class and replaced with a field in that other class.

I can only solve this issue by having two separate nested queries but this is way from efficient. Can you please show me how to do the following in a single query or more efficiently ;

 //get query result from database
        ParseQuery<ParseObject> query = ParseQuery.getQuery("access");
        query.whereStartsWith("tokenid", "prefix");
        query.findInBackground(new FindCallback<ParseObject>() {
            @Override
            public void done(List<ParseObject> objects, ParseException e) {
               for (int i=0; i<objects.size(); i++) {
                   String reportField1 = objects.get(i).getString("name");
                   String lookup = objects.get(i).getString("cityID");

                   //start the second query
                   ParseQuery<ParseObject> query2 = ParseQuery.getQuery("cities");
                   query2.whereEqualTo("cityID", lookup);
                   query2.getFirstInBackground(new GetCallback<ParseObject>() {
                       @Override
                       public void done(ParseObject object, ParseException e) {
                           String reportField2 = object.getString("cityname");
                       }
                   });
               }
            }
        });

Solution

  • What you're looking for is called pointer in Parse. Instead of storing cityID on your access object, store a pointer to a cities object and include it in your query.

    Here is an example from the Android guide

    ParseQuery<ParseObject> query = ParseQuery.getQuery("Comment");
    
    // Retrieve the most recent ones
    query.orderByDescending("createdAt");
    
    // Only retrieve the last ten
    query.setLimit(10);
    
    // Include the post data with each comment
    query.include("post");
    
    query.findInBackground(new FindCallback<ParseObject>() {
      public void done(List<ParseObject> commentList, ParseException e) {
        // commentList now contains the last ten comments, and the "post"
        // field has been populated. For example:
        for (ParseObject comment : commentList) {
          // This does not require a network access.
          ParseObject post = comment.getParseObject("post");
          Log.d("post", "retrieved a related post");
        }
      }
    });
    

    By storing a pointer on your access object, you can get the corresponding cities object simply by including it in your query.