在我的 CoreData 模型中,我有一个使用中间实体建模的 n2n 关系:
Person [1<--] Person2Appointment [-->1] Appointment
The Person2Appointment
实体看起来像这样:
@interface Person2Appointment : NSManagedObject
// attributes
@property (nonatomic, retain) NSNumber * participationState;
// relations
@property (nonatomic, retain) Person * person;
@property (nonatomic, retain) Appointment * appointment;
...
@end
(这两种关系也被建模为反向关系Person
and Appointment
实体)
我想获取所有人过去所有约会的计数。
在 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 一起使用:
// 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 日志记录后,core-data 似乎执行了正确的语句:
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>";
}
这是核心数据中的错误吗?
我在这里做错了什么吗?
或者还有其他方法可以实现这一目标吗?