3

guys i'm working on a android project for my DB course and i'm using realm DB but the problem is that i just found that realm has no foreign keys(realm is NOT a relational DB) so i was wondering if there is any other solution to use as a foreign key?

i was thinking about using class composition but would it work ?

abdullah
  • 157
  • 2
  • 8

1 Answers1

4

Realm has the concept of "relationships" (otherwise called as "links").

To-one relationship:

public class A extends RealmObject {
    B b;
}

To many relationship:

public class A extends RealmObject {
    RealmList<B> bs;
}

And for either of those relationships, there exists an inverse relationship (Realm Java 3.5.0+)

public class A extends RealmObject {
    B b;

    RealmList<B> bs;
}

public class B extends RealmObject {
    @LinkingObjects("b")
    private final RealmResults<B> fromB = null;

    @LinkingObjects("bs")
    private final RealmResults<B> fromBs = null;
}

If an object is unmanaged, then insertOrUpdate()/copyToRealmOrUpdate() will insert both A and its instance B into the Realm.

If an object is managed, then the object you set as value must be managed as well.

A a = realm.createObject(A.class);
a.setB(realm.createObject(B.class)); // or copyToRealmOrUpdate(b) or .findFirst() etc
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428