Migration Relationship To-One to To-Many Result on Empty NSSet

64 Views Asked by At

I encounter a problem when I migrate models.

Firstly, I had a user with an article. I made models like this:

Model v1

Now, I made a second version for the models like this:

Model v2

And in my AppDelegate, I call MagicalRecord.setupAutoMigratingCoreDataStack().

The migration works, but the article list on user is empty.

Does anyone know how to automatically set the list with the previous article set on user?

1

There are 1 best solutions below

0
Nguyen G On

You should set relationship type on user is "To many", and relationship type on article is "To one".

This will provide you an One-many relationship on the database which means one user can have many articles.

For accessing array of articles in first user, use:

let user = User.mr_findFirst()!
let articleList = user.article?.allObjects as! [Article]
for anArticle in articleList {
     // Do something here
}

Or in all users:

let userList = User.mr_findAll() as! [User]
for user in userList {
     let articleList = user.article?.allObjects as! [Article]
     for anArticle in articleList {
          // Do something here
     }
}