Nozbe / WatermelonDB

🍉 Reactive & asynchronous database for powerful React and React Native apps ⚡️
https://watermelondb.dev
MIT License
10.49k stars 589 forks source link

Many to Many relationships not working #857

Open RajatKumarChahar opened 3 years ago

RajatKumarChahar commented 3 years ago

I've a app where we have groups and memebers. Group can have multiple members and a member can be a part of multiple groups. I designed the schema as per documentation. But I'm unable to get the members of the group.

schema.js

import {appSchema, tableSchema} from '@nozbe/watermelondb';

export const mySchema = appSchema({
  version: 8,
  tables: [
    tableSchema({
      name: 'groups',
      columns: [
        {name: 'name', type: 'string'},
      ],
    }),
    tableSchema({
      name: 'members',
      columns: [
        {name: 'name', type: 'string'},
      ],
    }),
    tableSchema({
      name: 'group_member_membership',
      columns: [
        {name: 'group_id', type: 'string'},
        {name: 'member_id', type: 'string'},
      ],
    }),
  ],
});

GroupMemberMembership.js

import {field} from '@nozbe/watermelondb/decorators';
import {Model} from '@nozbe/watermelondb';

class GroupMemberMembership extends Model {
  static table = 'group_member_membership';

  static associations = {
    groups: {type: 'belongs_to', key: 'group_id'},
    members: {type: 'belongs_to', key: 'member_id'},
  };

  @field('group_id') group_id;
  @field('member_id') member_id;
}
export default LabelsContacts;

Group.js

/* eslint-disable prettier/prettier */
import {field, children, lazy} from '@nozbe/watermelondb/decorators';
import {Model, Q} from '@nozbe/watermelondb';

class Group extends Model {
  static table = 'groups';

  static associations = {
    group_member_membership: { type: 'has_many', foreignKey: 'group_id' },
  }

  @lazy
  members = this.collections
    .get('members')
    .query(Q.on('group_member_membership', 'group_id', this.id'));

  @field('name')
  name

export default Group;

generate.js

 const groupCollection = await db.collections.get('groups');
 const contactCollection = await db.collections.get('membes')
 const membeshipCollection = await db.collections.get('group_member_membership')

await groupCollection.create(group => {
      group.group_id = '1234'
      group.name = 'group1'
    })

await contactCollection.create(contact => {
      contact.contact_id = 'c234'
      contact.name = 'contact1'
    })

await membeshipCollection.create(membership => {
      membership.contact_id = 'c234'
      membership.group_id = '1234'
    })

Now when I query for group members i always get an empty array [ ]

withObservables(['group'], ({ group }) => ({
  members: group.members.observe(),
}))
KrisLau commented 2 years ago

You need to declare the id fields in GroupMemberMembership as @relation or @immutableRelation field. https://nozbe.github.io/WatermelonDB/Relation.html?highlight=many%20o#many-to-many-relation