How to pre-populate relational data (e.g. RealmList<Object>) into Realm

140 Views Asked by At

Is it possible to import relational data into Realm? My data model for ObjectA has a one-to-many relationship using List.

I pre-populated data using Realm Studio's import from CSV. Most of my data model is made up of Strings and Ints. But I'm not sure how to represent a List<> datatype in CSV.

As a workaround, I'll have my app populate the Realm with objects at runtime. But this approach uses one-time code, and this strikes me as basic functionality. There has to be a better way!

My data model:

class Person: Object {
    @objc dynamic var title: String = "" 
    @objc dynamic var id: Int = 0
}

class Dog: Object {
    @objc dynamic var id: Int = 0
    @objc dynamic var title: String = ""
    var owner = List<Person>()
}
1

There are 1 best solutions below

0
On BEST ANSWER

If you want to read in ‘relational data’ you could write an app to read that data, populate your realm objects and save it to realm.

Representing relational data in a flat file usually has some common keys that associate that data. For example people and dogs. The people file may look like this; persons id, name and favorite food

1234,jay,pizza
5678,cindy,steak

then the dogs file would look like this with the dog id, dog name and then the persons (owners) id

1111,rover,1234
2222,spot,1234
3333,scraps,5678

In the above example, jay owns rover and spot and cindy owns scraps.

The realm PersonClass object would be

class PersonClass: Object {
   @objc dynamic var person_id = ""
   @objc dynamic var person_name = ""
   @objc dynamic var fav_food = ""
   let dogList = List<DogClass>()
}

and then for the dogs

class DogClass: Object {
   @objc dynamic var dog_id = ""
   @objc dynamic var dog_name = ""
   @objc dynamic var person_id = ""
}

The process would be to read in the people (creating the people objects), read in the dogs, iterate over each dog and add it to that persons dogList - the person could be found by its person_id.

Ideally, it would best to include primary_keys with this structure.

Likewise, you could read all dogs and people into Realm Studio and the add the dogs to their respective people's dogList as well.

You can command-click on filenames to import multiple files into Realm Studio