Skip to content

Including Related Objects in Queries

Every time you hit a mobile network, it slows your users down and introduces another point of failure. So when you're designing your application, you need to take advantage of every opportunity to omit needless requests.

Parse's philosophy is to help make this easier by providing standard ways to reduce network requests. One example is caching queries, which lets you avoid resending requests you've already sent. Another example, which we've launched in the most recent version of the Parse SDK, is include functionality, inspired by the Ruby on Rails :include option.

When you have relational data, the includeKey: method in iOS and the include method in Android lets you specify that data from a relational field should be also fetched at the time of the initial query. For example, suppose each Song object has an associated Band in the band key. You might have an app that shows the top ten songs by sales, and you want to also retrieve information about the band without issuing an extra query. To fetch this data in iOS:

PFQuery *query = [PFQuery queryWithClassName:@"Song"];

// Retrieve the top songs by sales
[query orderByDescending:@"sales"];

// Limit to retrieving ten songs
query.limit = 10;

// Include the band data with each song
[query includeKey:@"band"];

// Issue the query
[query findObjectsInBackgroundWithBlock:^(NSArray *songs, NSError *error) {
    if (error) return;

    // Songs now contains the last ten songs, and the band field has
    // been populated. For example:
    for (PFObject *song in songs) {
        // This does not require a network access.
        PFObject *band = [song objectForKey:@"band"];
    }
}];

Read more about relational queries in the iOS documentation, Android documentation, or REST documentation.

Our goal is to provide developers with an easy and efficient way to get their job done. We're always interested in more feedback on how we can help you build great apps, so if you have great ideas for how Parse could help you, get in touch.

Have fun building apps!