【问题标题】:CoreData NSPredicate with many-to-many relationship具有多对多关系的 CoreData NSPredicate
【发布时间】:2010-06-23 20:28:36
【问题描述】:

我已经为人/标签关系建模。这是多对多的关系;一个人可以有多个标签,一个标签可以与多个人相关联。

我正在尝试运行查询以查看人员列表,这些人员已被标记为一组标记中的每个标记。例如:每个被标记为“FOO”和“BAR”的人。

这是我尝试但没有成功的代码。

NSPredicate *attributePredicate = [NSPredicate predicateWithFormat: 
                                       @"ALL personTags.tagName in %@", filtersArray];
[subPredicates addObject:attributePredicate];;

有没有办法解决这个问题?我使用 SqlLite 作为持久存储。 我的数据库中有大约 2000 人,大约有 100 个不同的标签,只有少数几个会同时应用标签。

【问题讨论】:

    标签: iphone core-data many-to-many


    【解决方案1】:

    反转您的查询并询问“self in %@”的标签,然后您可以对结果数组执行 KVC 操作,例如:

    NSArray *array = [results valueForKeyPath:@"@distinctUniionOfArrays.person"];
    

    这将为您提供您正在寻找的结果。请注意,这是在我的 iPad 上输入的,因此很可能是拼写错误。

    请参阅有关此主题的文档

    http://developer.apple.com/mac/library/iPad/index.html#documentation/Cocoa/Conceptual/KeyValueCoding/Concepts/ArrayOperators.html

    更新

    对不起,我误读了这个问题。我建议尝试子查询。如果无法访问您的数据结构,很难对其进行测试以使其完全正确,但这段代码应该让您走上正确的道路:

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:[NSEntityDescription entityForName:@"Person" inManagedObjectContext:moc]];
    [request setPredicate:[NSPredicate predicateWithFormat:@"(SUBQUERY(self.tags, $tag, ALL $tag.name in %@).count > 0)", tagNameArray]];
    
    NSError *error = nil;
    NSArray *results = [moc executeFetchRequest:request error:&error];
    NSAssert2(error == nil, @"Error fetchings tags: %@\n%@", [error localizedDescrption], [error userInfo]);
    

    【讨论】:

    • 嗨,Markus,我试了一下,但 @distinctUnionOfSets 返回两个或多个集合之间的并集。我需要的是这些集合之间的交集。对此有何建议?
    • 你是个天才!这非常有效: NSPredicate *attributePredicate = [NSPredicate predicateWithFormat: @"(SUBQUERY(self.personTags, $tag, $tag.tagName IN %@).@count > %d)", filtersArray, [filtersArray count]-1] ;
    • 您的 filtersArray 集合是过滤器对象本身的数组吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多