문제

This is my core data model:

Conference
==========
name

events (to-many relationship to Event object)

Event
======
date
type (int - private=0, public=1)

conference (to-one relationship to Conference object)

So conference can have many events, and event has only one conference:

Conference <------>> Event

I have a complex fetch that I'm not sure how to do, this is what I need:

The 3 top conferences with the most public events AND meet the basic conditions, meaning:
1. conference has at least 1 private event.
2. conference has at least 5 public event.
3. should be calculated based on the last 10 days

I'm not sure if I should query the Conference objects directly or query the Event objects and than filter the appropriate conferences using event.conference

Efficiency is important, so if possible to use fetch limit or other optimization.

도움이 되었습니까?

해결책

You can use SUBQUERY to do it in a single fetch request:

 NSDateComponents* components = [[NSCalendar currentCalendar] components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:[NSDate date]];
    [components setDay:[components day] - 10];
    NSDate* tenDaysAgo = [[NSCalendar currentCalendar] dateFromComponents:components];

    NSFetchRequest* fetchRequest = [NSFetchRequest fetchRequestWithEntityName:NSStringFromClass([Conference class])];
    fetchRequest.predicate = [NSPredicate predicateWithFormat:@"SUBQUERY(events, $event, $event.type = 0 AND $event.date > %@).@count >= 1 AND SUBQUERY(events, $event, $event.type = 1 AND $event.date > %@).@count >= 5", tenDaysAgo, tenDaysAgo];
fetchRequest.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"events.count" ascending:NO];
    fetchRequest.fetchLimit = 3; 

NOTE: sort descriptor with events.count will only work for in-memory store or binary store, but it will crash for SQLite store (more about it here). In this case you should sort and limit results after the fetch.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top