我有2个这样的表:
Users
user_id (pk)
email
name
inGroups (many to many relationship with groups)
Groups
group_id (pk)
group_name
whoseUsers (many to many relationship with users)
我的核心数据代码如下:
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Users"];
request.predicate = [NSPredicate predicateWithFormat:@"user_id = %@ AND inGroups = %@", user_id, group_id];
运行此操作时,我会抛出异常:
@"to-many key not allowed here"
如何使其正常工作?
答案 0 :(得分:2)
要查找给定user_id
的用户,这些用户是具有给定group_id
的群组的成员,
使用
[NSPredicate predicateWithFormat:@"user_id = %@ AND ANY inGroups.group_id = %@",
user_id, group_id];
答案 1 :(得分:0)
首先不要使用= use ==喜欢这个“user_id ==%@ AND inGroups ==%@”其次如果是多对多的关系那么它就是一个NSSet。你在这里尝试做的是将NSSet关系与group中的group_id进行比较。 编辑你应该做这样的事情 NSFetchRequest * request = [NSFetchRequest fetchRequestWithEntityName:@“Users”];
request.predicate = [NSPredicate predicateWithFormat:@“user_id ==%@ AND inGroups CONTAINS%@”,user_id,group];
其中group是actuall Groups对象