Nozbe / WatermelonDB

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

Support for more than one association to the same query #1577

Open danieleformichelli opened 1 year ago

danieleformichelli commented 1 year ago

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 🙌

Dallas62 commented 1 year ago

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
}
danieleformichelli commented 1 year ago

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? 🤔

PEZO19 commented 1 year ago

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