Support for more than one association to the same query
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 🙌
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
}
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? 🤔
@danyf90 Does this help to you? https://github.com/Nozbe/WatermelonDB/issues/885#issuecomment-1712833371
@danieleformichelli Did you ever figure out a solution to this? What did you end up doing? Thanks!