【问题标题】:Core Data - Select by relationship核心数据 - 按关系选择
【发布时间】:2014-11-07 18:28:41
【问题描述】:

FatherSon 实体之间存在一对多关系,其中 Father 可能没有或 N Son。使用Core Data,我如何获得所有Son,基于我对Father的搜索。

例如:我有一个Father,他拥有Id 1。我需要获取所有Son 拥有FatherId 1。

【问题讨论】:

    标签: ios objective-c iphone core-data swift


    【解决方案1】:

    这里是一个使用 NSManagedObject 的示例(子类化更容易)。

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:[NSEntityDescription entityForName:@"Father" inManagedObjectContext:your_managedObjectContext]];
    // You speak about you use Id, but is word reserved better use resourceId or something like that
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"resourceId=1"];
    [request setPredicate:predicate];
    NSArray *result = [your_managedObjectContext executeFetchRequest:request error:nil];
    NSManagedObject *father_Id1 = [result firstObject];
    NSSet *sons = [father_Id1 valueForKey:@"theNameOfYourRelationshipSons"];
    

    【讨论】:

    • 它是相同的,但在两个方向。想象一下,在这种情况下,PartOfParent (Mather and Father) 不是父亲。在这种情况下是多对多的,代码是一样的。您可以使用实体 Son 发出其他请求(它是谓词,resourceId = 5 的儿子),并询问其父母。
    • 当关系是一个,并且你调用 [theNSManagedObject valueForKey:@"theRelationShipToOne"] 你有和对象(和 NSManagedObject)。如果它的数量很多并且你调用 [theNSManagedObject valueForKey:@"theRelationShipToMany"] 你会有很多对象(以及带有 NSManagedObject 的 NSSet)
    【解决方案2】:

    这是一个快速代码,用于获取所有父亲为 id = 5 的儿子

    let fetchRequest = NSFetchRequest(entityName: "Son")
    fetchRequest = NSPredicate(format: "father.id == %@", argumentArray: [id])
    let fathers = context.executeFetchRequest(fetchRequest, error: nil) as? [Father]
    

    【讨论】:

    • 好的,谢谢!如果是多对多关系呢?
    • 如果Son实体中有fathers关系(这在现实生活中永远不会发生:))谓词格式为fathers.id == %@
    • 谢谢!是的,这只是一个猜测呵呵
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-24
    • 1970-01-01
    相关资源
    最近更新 更多