Skip to content

ManyToMany Relationship

The ManyToMany relationship represents a many-to-many relationship where two models are related through a join table.

Explanation

For example, a User belongs to many Roles, and a Role belongs to many Users:

Defining the Relationship

The relationship is defined in your model configuration under the relationships property as a tuple:

typescript
[ManyToMany, foreignModelTable: string, joinTable: string, joinTableForeignKeyForOriginating: string, joinTableForeignKeyForTarget: string, foreignPrimaryKey?: string, originatingPrimaryKey?: string]

Parameters

  • ManyToMany: The relationship type.
  • foreignModelTable: The table name of the related model.
  • joinTable: The join table name.
  • joinTableForeignKeyForOriginating: The foreign key in the join table referencing the originating model.
  • joinTableForeignKeyForTarget: The foreign key in the join table referencing the target model.
  • foreignPrimaryKey (optional): The primary key in the foreign model (defaults to 'id').
  • originatingPrimaryKey (optional): The primary key in the originating model (defaults to 'id').

Example

typescript
{
  models: {
    users: {
      schema: '++id, email, createdAt, updatedAt',
      properties: ['id', 'email', 'password'],
      primaryKey: 'id',
      relationships: {
        roles: [ManyToMany, 'roles', 'role_user', 'user_id', 'role_id'], 
      }
    },
    roles: {
      schema: '++id, name',
      properties: ['id', 'name'],
    },
    role_user: {
      schema: 'user_id, role_id',
      properties: ['user_id', 'role_id'],
    }
  }
}

Accessing the Relationship

typescript
const user = await User.find(1)
const roles = await user.roles

roles.forEach(role => {
  role.onChange((updatedRole) => {
    console.log('Role updated:', updatedRole)
  })
})

user.onPropertyChange('roles', (newRoles, oldRoles) => {
  console.log('Roles collection changed:', { new: newRoles, old: oldRoles })
})