Reputation: 5078
How to determine if Bookshelf hasMany
relation has not been loaded at all or is it just empty?
According to Bookshelfjs documentation:
The related method returns a specified relation loaded on the relations hash on the model, or calls the associated relation method and adds it to the relations hash if one exists and has not yet been loaded. Model#related
If giving { withRelated: ['relation'] }
to fetch
, the relations are loaded as can be seen output if setting debug: true
to Knex, and related('relation')
contains the models if they existed.
But, if there were no related models the return value of related('relation')
seems to be the same as when not giving the withRelated
option at all, ie. it cannot be used to determine if the data has been loaded previously or not. Calling related('relation').fetch()
multiple times results in as many SQL queries.
Am I doing something fundamentally wrong or do I really just need to build my own cache for the relations? I have relation which I need to filter, and would like the model instance to have nice getters for the filtered data without having the relations being refetched from the database on every call.
Upvotes: 2
Views: 727
Reputation: 12985
There is no official way, see the GitHub issue.
But if you want, you can check it in a way which is not officially supported:
modelInstance.relations[relationName]
// e.g.
user.relations.organization // undefined if not fetched yet
Upvotes: 1