ios – CoreData获取关系计数请求和另一个关系的组(m2n)

在我的CoreData模型中,我有一个使用中间实体建模的n2n关系:

Person [1<--] Person2Appointment [-->1] Appointment

Person2Appointment实体如下所示:

@interface Person2Appointment : NSManagedObject

// attributes
@property (nonatomic, retain) NSNumber * participationState;

// relations
@property (nonatomic, retain) Person * person;
@property (nonatomic, retain) Appointment * appointment;
...
@end

(这两种关系也被建模为人和任命实体的反向关系)

我想取一个所有人过去约会的统计数.

在SQL中它看起来像:

select count(fk_appointment), fk_person 
  from person2appointment t0
  left join appointment t1 on t0.fk_appointment = t1.pk
where t1.date < ...
group by fk_person;

我尝试使用带有我的fetch-request的count-function表达式,方法如下:

 // create a fetch request for the Person2Appointment entity (category method)
NSFetchRequest* fetch = [Person2Appointment fetchRequest];
fetch.resultType = NSDictionaryResultType;

// count appointments
NSExpression* countTarget = [NSExpression expressionForKeyPath: @"appointment"];
NSExpression* countExp = [NSExpression expressionForFunction:@"count:" arguments: @[countTarget]];
NSExpressionDescription* countDesc = [[NSExpressionDescription alloc]init];
countDesc.name=@"count";
countDesc.expression = countExp;
countDesc.expressionResultType =  NSDecimalAttributeType;

fetch.propertiesToFetch = @["person", countDesc];
fetch.propertiesToGroupBy = ["person"];

fetch.predicate = ...;

打开SQL日志后,核心数据似乎执行正确的语句:

SELECT t0.ZPERSON, COUNT( t0.ZAPPOINTMENT) 
  FROM ZPERSON2APPOINTMENT t0 
  JOIN ZAPPOINTMENT t1 ON t0.ZAPPOINTMENT = t1.Z_PK 
  WHERE  t1.ZSTARTDATE > ? GROUP BY  t0.ZPERSON 

但结果数组中的字典不包含数字计数,而是包含约会实体:

Printing description of d:
{
    count = "0xd0000000000c0018 <x-coredata://BABCBD2E-05AB-4AA5-AC2B-2777916E4EDF/Appointment/p3>";
    person = "0xd0000000000c0016 <x-coredata://BABCBD2E-05AB-4AA5-AC2B-2777916E4EDF/Person/p3>";
}

这是核心数据中的错误吗?

我在这里做错了吗?

或者有另一种方法来实现这一目标吗?

最佳答案 这看起来像是CoreData中的一个错误,但经过一些实验,我认为你可以通过修改计数表达式来实现你想要的,计算你的Person2Appointment实体的属性,而不是计算约会关系(计数应该是相同的,因为关系是一个,除非你有空值?):

NSExpression* countTarget = [NSExpression expressionForKeyPath: @"participationState"];
NSExpression* countExp = [NSExpression expressionForFunction:@"count:" arguments: @[countTarget]];

如果您确实需要担心空值,可以使用:

NSExpression *countTarget = [NSExpression expressionForEvaluatedObject];
点赞