MagicalRecord:一对多关系

MagicalRecord: one to many relationship

我不太确定这是否是正确的方法

我想在实体A和B之间建立一对多的关系,这样A可以引用B的多条记录,但B只能引用A的一条记录

我的问题是如何使用 MagicalRecords 执行此操作...我熟悉单个实体的基本获取和创建

但不知道如何获取、创建、更新具有关系的实体

"how to do this with MagicalRecords" 是什么意思?因为这不是由 MagicalRecords 处理的。 它们都在 coredata 模型文件中设置。 例如,对于我的项目,我正在实施 IM 功能。 1.一次对话->多条消息 2. 一条消息->一次对话

这是数据模型的设计。 随时问我有关 Coredata + MR 的任何问题 干杯!

首先要注意CoreData的'context'。我通常使用 [MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) {}];方法,并在块内创建实体。

我将以我上面展示的案例为例,

要将 "message" 保存到 "conversation" 实体,

ChatConversation* chatConversation = [ChatConversation MR_findFirstByAttribute:@"conversationID" withValue:<your value> inContext:localContext];

^先看看有没有用find first by attribute方法创建的entity

ChatMessage* chatMessage = [ChatMessage MR_createInContext:localContext];
   [chatMessage set.....];
   ......

if(!chatConversation){
   //You need to create a new chatConversation entity
   chatConversation = [ChatConversation MR_createInContext:localContext];
   ......
 }
   [chatMessage setChatConversation:chatConversation];
  1. 如果您想从聊天对话中获取所有消息,只需使用自定义谓词获取所有消息

    -(NSFetchedResultsController *)fetchedResultsController {
    
     if(!_fetchedResultsController)
         _fetchedResultsController = [ChatMessage MR_fetchAllSortedBy:@"createdAt" ascending:TRUE withPredicate:[NSPredicate predicateWithFormat:@"%K == %@", @"conversation.conversationID",self.conversationObject.conversationID] groupBy:nil delegate:self];
    
    return _fetchedResultsController;
    }