Search code examples
react-nativerealmmobile-development

How can I join two tables with REALM


I am new to REALM and I am trying to join two tables but I can't find information of sql query for realm (I am using React Native)

Tables are ChatRoom and Message. ChatRoom has multiple Messages. I would like to get all chatrooms with only one most lastest message for each chatroom.

ChatRoom.schema = {
    name: 'fcm_chat_room',
    primaryKey: 'chat_room_id',
    properties: {
        chat_room_id:  'string',
        chat_room_name: {type: 'string', default: ''},
        chat_room_date: 'date'
    }
};

Message.schema = {
    name: 'fcm_message',
    primaryKey: 'message_id',
    properties: {
        message_id:  'string',
        chat_room_id: 'string',
        sender_id: 'string',
        sender_reg_id: 'string',
        message: 'string',
        msg_date: 'date',
        is_read: {type: 'bool', default: false}
    }
};

Solution

  • try this example, it will help you to join table in realm database.

        const CarSchema = {
     name: 'Car',
     properties: {
       make:  'string',
       model: 'string',
       miles: {type: 'int', default: 0},
     }
    };
    const PersonSchema = {
     name: 'Person',
     properties: {
       name:     'string',
       birthday: 'date',
       cars:     {type: 'list', objectType: 'Car'},
       picture:  {type: 'data', optional: true}, // optional property
     }
    };
    // Initialize a Realm with Car and Person models
    let realm = new Realm({schema: [CarSchema, PersonSchema]});
    
    Combine React Native
    
    const Realm = require('realm');
    
    class  extends Component {
    render() {
      let realm = new Realm({
        schema: [{name: 'Dog', properties: {name: 'string'}}]
      });
    
      realm.write(() => {
        realm.create('Dog', {name: 'Rex'});
      });
    
      return (
    
    
            Count of Dogs in Realm: {realm.objects('Dog').length}
    
    
      );
    }
    }