Search code examples
iosparse-platformpfquery

Query ascending by the NSDate field of pointer


I have 2 Classes: Event and Participant. Here are their attributes.

Event:

  • NSDate startingDate
  • NSString title

Participant:

  • PFUser user
  • Event event
  • and some other attributes I'll need later

When a user want to participate on event I create Participant object and assign event to it and also user. Later on I want to get all the Events that have Participants for current user. And this events need to be ordered by startingDate ascending.

I created a query that gets all the participants for current user, and the I read the event addribute from it, but I really need that events will be ordered by its starting date. How should I approach this. I created Participant class because I need to save the data that user create for this event.

EDIT: I tried this one:

PFQuery *eventQuery = [Event query];
[eventQuery orderByAscending:@"startingDate"];

PFQuery *participantQuery = [Participant query];
[participantQuery includeKey:@"user"];
[participantQuery includeKey:@"event"];
[participantQuery whereKey:@"user" equalTo:[PFUser currentUser];
[participantQuery whereKey:@"event" matchesQuery:eventQuery];
[participantQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    NSMutableArray *eventsArray = [NSMutableArray new];
    for (Participant *participant in objects) {
        [eventsArray addObject:participant.event];
    }
}];

here I can use eventsArray

But this one just ignores the [eventQuery orderByAscending:@"startingDate"]; line. I also need to ask for opinion that I choose the approach to first fetch the Participants and then put them in a for loop to get their events and saves them in an array. Is this good? It seems wrong, why do I need to fetch participant if I acctualy need Events for User.


Solution

  • If your Event class had a reference to the Participant class (either as Array or Relation<Participant> depending on size) named participants, then you could do something like the following:

    PFQuery *eventQuery = [Event query];
    
    PFQuery *participantQuery = [Participant query];
    [participantQuery whereKey:@"user" equalTo:[PFUser currentUser]];
    
    [eventQuery whereKey:@"participants" matchesQuery:participantQuery];
    [eventQuery orderByAscending:@"startingDate"];
    [eventQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        // objects array contains your Event objects
    }];
    

    You just need to update your code that creates Participant objects to also add it to the participants column of the Event object.