Objection.js: Instance method $relatedQuery returns undefined

Created on 11 Dec 2019  路  6Comments  路  Source: Vincit/objection.js

So basically I have 3 models: Event, User and Ticket.
Ticket connects Event and User as it has eventId and userId.
And so this is a way I use relations to collect all in the event participating users:

users: {
    relation: Model.HasOneThroughRelation,
    modelClass: 'user',
    join: {
        from: 'events.id',
        through: {
            from: 'tickets.eventId',
            to: 'tickets.userId'
        },
        to: 'users.id'
    }
}

in relationMappings() static method.

And there's where I encountered something strange. If there's no tickets for specific event and so no users, static Event.relatedQuery<User>('users').for(event.id); works fine - returns empty list. However if I use event instance event.$relatedQuery<User>('users'); it returns undefined.
In docs it's said that instance method is just a shortcut for static method, but both returns different results in this case.

Node - 12.13.1
Objection - 2.0.5
knex - 0.20.4

bug

All 6 comments

This is the implementation:

  $relatedQuery(relationName, trx) {
    return this.constructor.relatedQuery(relationName, trx).for(this);
  }

so as long as event has an id (this in the implementation), it is just a call-trough.

The difference is that relatedQuery can return relations for multiple items. You can even provide a subquery to for method. The result needs to be an array because we cannot know whether to expect one or many items and changing the result type depending on the result count would be insanely stupid.

With $relatedQuery we know there will only be one or zero results, because it's called for a single model instance and users is a HasOneThroughRelation. This is how $relatedQuery has always worked and it makes sense.

I can add a mention about this difference in the docs.

@koskimas Thanks for a quick reply, I understand now. Also just curious why there's no HasOneThroughRelation relation for multiple results?

It's called ManyToManyRelation.

Ah, crap.

If you call Event.relatedQuery('users').for([event1, event2]) you get one single result, and all others are lost. It seems that the static relatedQuery is inconsistent in this case after all. I'll fix that asap.

I didn't quite understood ManyToManyRelation so I was thinking it doesn't support through. And for a bug, I just checked out static relatedQuery with multiple ids and relations but its seems to be working fine for me.

The documentation is filled with examples that use through in ManyToManyRelation. There's also the example project that should make it very clear.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Ahlid picture Ahlid  路  3Comments

louis-etne picture louis-etne  路  4Comments

officer-rosmarino picture officer-rosmarino  路  4Comments

bsdo64 picture bsdo64  路  3Comments

zuck picture zuck  路  4Comments