gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 05:53:09 25 4
gpt4 key购买 nike

在我的 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

(这两种关系也被建模为 PersonAppointment 实体的反向关系)

我想获取所有人过去所有约会的计数。

在 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;

我尝试通过以下方式在我的获取请求中使用计数函数表达式:

 // 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>";
}

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

我是不是做错了什么?

或者有其他方法可以实现吗?

最佳答案

在我看来这像是 CoreData 中的一个错误,但经过一些实验后,我认为您可以通过修改计数表达式来实现您想要的,以计算您的 attribute Person2Appointment 实体,而不是计算 Appointment 关系(计数应该相同,因为关系是一对一的,除非你有空值?):

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

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

NSExpression *countTarget = [NSExpression expressionForEvaluatedObject];

关于ios - CoreData 获取关系计数和另一个关系分组的请求 (m2n),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27312615/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com