Search code examples
databasedatabase-designrealmrealm-list

Creating a bridge table equivalent realm class?


I am designing a database which I am planning to implement on Android using Realm. I am still exploring and reading about using the library but I have one question that concerns me. Is it possible to implement a bridge table (see the diagram bellow) using Realm?

From what I read in the "Relationships" section in the docs link, I can use RealmList object to do many to many relationships. For example, for the "User_Activity" table. However, I an still unsure how to "convert" the database design into Realm class equivalent.

enter image description here


Solution

  • public class User extends RealmObject {
        @PrimaryKey
        private String userId;
    
        private String password;
    
        @Index
        private String username;
    
        private String paGoal; // ?
    
        private long maxInactivityInterval;
    
        private RealmList<UserActivity> userActivities;
    
        private Activity currentActivity; // optional
    }
    
    public class UserActivity extends RealmObject {
        @PrimaryKey
        private String userIdAndActivityIdAndDate; // userid_activityid_2017-01-23
    
        @Index
        private Date date;
    
        private long duration;
    
        private User user;
    
        @Index
        private String userId;
    
        private Activity activity;
    
        @Index
        private String activityId;
    }
    
    public class Activity extends RealmObject {
        @PrimaryKey
        private String activityId;
    
        @Index
        private String type;
    }
    

    I think this schema would work fine for you.