Reputation: 1480
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.
Upvotes: 5
Views: 6472
Reputation: 1951
it's not supported by realm till today,
you can pass your primary keys to the consturcor and mark a field as @PrimaryKey
, do it this way :
public class ProjectsUsers extends RealmObject {
@PrimaryKey
private String newPrimaryKey;
private String key1, key2;
/// other staff
public ProjectsUsers() {
}
public ProjectsUsers(String key1, String key2) {
this.newPrimaryKey = key1 + "|" + key2;
this.key1 = key1;
this.key2 = key2;
/// other staff set
}
}
Upvotes: 0
Reputation: 21
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
Upvotes: 1
Reputation: 3096
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
Upvotes: 2
Reputation: 15991
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?
Upvotes: 7