Search code examples
parse-platformpfquery

select last 20 entries from a table for each non unique id from a list of ids, all in one query


i have a message table that has the fallowing structure

objectId | groupId | senderId | message

It is a table that contains all the messages from all my app's groups. How can i perform a query so that i get the last 20 messages for each of an array of group ids?

EXAMPLE

objectId | groupId | senderId | message

1234 | 1 | 234 | "hello!"

1235 | 1 | 123 | "hello to you too!"

1236 | 2 | 456 | "test"

1237 | 3 | 678 | "lol"

i would like to extract the last 20 messages for both groups 1 and 2. How can i do so in a single query? Can it be done?


Solution

  • I think you should be able to do this with an "or" query.

    I made some guesses as to class names and column types. Please edit those values as necessary to match your actual data structure.

    Try this:

    - (void)runQuery {
        PFQuery *query1 = [PFQuery queryWithClassName:@"message"];
        [query1 addDescendingOrder:@"createdAt"];
        [query1 whereKey:@"groupId" equalTo:@(1)];
        query1.limit    = 20;
    
        PFQuery *query2 = [PFQuery queryWithClassName:@"message"];
        [query2 addDescendingOrder:@"createdAt"];
        [query2 whereKey:@"groupId" equalTo:@(2)];
        query2.limit    = 20;
    
        PFQuery *both   = [PFQuery orQueryWithSubqueries:@[query1, query2]];
        [both findObjectsInBackgroundWithBlock:^(NSArray *messages, NSError *error) {
            // You should have up to 40 message items,
            // up to 20 from each query
    
        }
         ];
    }