5

I am writing an app using the Realm.io database that will pull data from another, server database. The server database has some tables whose primary keys are composed of more than one field. Right now I can't find a way to specify a multiple column key in realm, since the primaryKey() function only returns a String optional.

This one works: //index override static func primaryKey() ->String? { return "login" }

But what I would need looks like this:

//index
override static func primaryKey() ->[String]?
{
    return ["key_column1","key_column2"]
}

I can't find anything on the docs on how to do this.

tutiplain
  • 1,427
  • 4
  • 19
  • 37

3 Answers3

7

Supplying multiple properties as the primary key isn't possible in Realm. At the moment, you can only specify one.

Could you potentially use the information in those two columns to create a single unique value that you could use instead?

TiM
  • 15,812
  • 4
  • 51
  • 79
  • Since I will have many tables, most of them with multiple column keys, this is not practical. It would require a lot of extra logic just to handle the table IDs. – tutiplain Aug 05 '15 at 21:09
  • Accepted as answer since it answers my original question: it can't currently be done. – tutiplain Aug 05 '15 at 21:10
2

It's not natively supported but there is a decent workaround. You can add another property that holds the compound key and make that property the primary key.

Check out this conversation on github for more details https://github.com/realm/realm-cocoa/issues/1192

Guy
  • 2,883
  • 1
  • 32
  • 39
0

You can do this, conceptually, by using hash method drived from two or more fields. Let's assume that these two fields 'name' and 'lastname' are used as multiple primary keys. Here is a sample pseudo code:

StudentSchema = {    
    name: 'student',
    primaryKey: 'pk',
    properties: {
        pk: 'string',
        name: 'string',
        lastname: 'string',
        schoolno: 'int'
    }
};
...
...
// Create a hash string drived from related fields. Before creating hash combine the fields in order.
myname="Uranus";
mylastname="SUN";
myschoolno=345;
hash_pk = Hash( Concat(myname, mylastname ) ); /* Hash(myname + mylastname) */
// Create a student object
realm.create('student',{pk:hash_pk,name:myname,lastname:mylastname,schoolno: myschoolno});

If ObjectId is necessary then goto Convert string to ObjectID in MongoDB

NeptunB
  • 11
  • 2