WatermelonDB icon indicating copy to clipboard operation
WatermelonDB copied to clipboard

Support for more than one association to the same query

Open danieleformichelli opened this issue 2 years ago • 4 comments

The Model.associations field is defined as a map from a table name to a BelongsTo or HasMany association.

Unless I'm missing something, with this model I can't define multiple associations to the same table.

For example, following the blog example, if I would like to keep track of a post author and post last editor I would need something like:

class Post extends Model {
  static table = 'posts'
  static associations = {
    users: [
      { type: 'belongs_to', key: 'creator_id' },
      { type: 'belongs_to', key: 'last_editor_id' },
    ]
  }
}

but the current API only supports one AssociationInfo per table.

If that's already possible, I'll be happy to try to add an example to the documentation 🙌

danieleformichelli avatar Mar 31 '23 08:03 danieleformichelli

Hi @danyf90,

Maybe you want to do this:

class Post extends Model {
  static table = 'posts'
  static associations = {
    user_creator: { type: 'belongs_to', key: 'creator_id' },
    user_last_editor:  { type: 'belongs_to', key: 'last_editor_id' },
  }
  @relation('user_creator', 'creator_id') creator
  @relation('user_last_editor', 'last_editor_id') last_editor
}

Dallas62 avatar Apr 15 '23 20:04 Dallas62

Hi @danyf90,

Maybe you want to do this:


class Post extends Model {

  static table = 'posts'

  static associations = {

    user_creator: { type: 'belongs_to', key: 'creator_id' },

    user_last_editor:  { type: 'belongs_to', key: 'last_editor_id' },

  }

  @relation('user_creator', 'creator_id') creator

  @relation('user_last_editor', 'last_editor_id') last_editor

}

Isn't the key of associations supposed to be the name of the other table? 🤔

danieleformichelli avatar Apr 15 '23 21:04 danieleformichelli

@danyf90 Does this help to you? https://github.com/Nozbe/WatermelonDB/issues/885#issuecomment-1712833371

PEZO19 avatar Sep 10 '23 15:09 PEZO19

@danieleformichelli Did you ever figure out a solution to this? What did you end up doing? Thanks!

tom-at-pixel avatar Aug 03 '25 19:08 tom-at-pixel