核心数据:多对多关系的 NSPredicate.(“此处不允许使用多对多键") [英] Core Data: NSPredicate for many-to-many relationship. ("to-many key not allowed here")
问题描述
我有两个名为类别"和文章"的实体,它们具有多对多的关系.我想形成一个谓词,它搜索所有 category.name 等于某个值的文章.我有以下几点:
I have two entities named "Category" and "Article" which have a many to many relationship. I want to form a predicate which searches for all articles where category.name is equal to some value. I have the following:
NSEntityDescription *entityArticle = [NSEntityDescription entityForName:@"Article" inManagedObjectContext:managedObjectContext];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"categories.name == [cd] %@", category.name];
[request setSortDescriptors:sortDescriptors];
[request setEntity:entityArticle];
[request setPredicate:predicate];
NSMutableArray *results = [[managedObjectContext executeFetchRequest:request error:nil] mutableCopy];
if ([results count] > 0)
NSLog(@"Results found.");
else
NSLog(@"NO results found.");
[request release];
[sortDescriptor release];
[sortDescriptors release];
我收到的错误是 *** 由于未捕获的异常NSInvalidArgumentException"而终止应用程序,原因:此处不允许使用对多键"
是否有任何选项可以检索所需的数据?
Are there any options to retrieve the desired data?
推荐答案
您正在尝试将集合 (categories.name
) 与标量值 (category.name代码>).您需要使用集合比较器 (
CONTAINS
),或使用谓词修饰符 (ANY
/ALL
/SOME
> 等).
You're trying to compare a collection (categories.name
) to a scalar value (category.name
). You need to either use a collection comparator (CONTAINS
), or use a predicate modifier (ANY
/ALL
/SOME
, etc).
尝试使用:
[NSPredicate predicateWithFormat:@"ANY categories.name =[cd] %@", category.name];
或者:
[NSPredicate predicateWithFormat:@"categories.name CONTAINS[cd] %@", category.name];
这篇关于核心数据:多对多关系的 NSPredicate.(“此处不允许使用多对多键")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!