I am using objection.js, and I have this model, and would like to get other object instances that share the same property value as the current instance, e.g.
Example of model structure: SomeModel { property1: 'string', } Objection.js: class SomeModel extends Model{ static get tableName() { return 'some_model' } }
and I would like to create a custom property that filters the model for others that share the same value so that I can get modelInstance.customProperty and it returns a list of filtered objects. Whats the best way to do it? I have tried using a virtualAttribute to no avail since queries should be in an async function, and virtual attribute doesnt support that
class SomeModel extends Model{ static get tableName() { return 'some_model' } static get virtualAttributes() { return ['customProperty']; } async customProperty() { return SomeModel.query().where('property1', this.property1) } }
I know that this approach is wrong but I hope you get an idea of what I am looking for
Edit: So I tried using this approach instead, but Im not sure if its the best way to do it
class SomeModelHelper extends Model { static get tableName() { return 'some_model'; } } class SomeModel extends Model{ static get tableName() { return 'some_model'; } static get virtualAttributes() { return ['customProperty']; } async $afterFind(args) { await SomeModelHelper.query() .where('property1', this.property1) .then(results => this.customProperty = results); } }
Thanks to @rashomon's comment, I managed to solve it with
class SomeModel extends Model{ static get tableName() { return 'some_model'; } $afterFind(args) { SomeModel.query() .where('property1', this.property1) .then(results => this.customProperty = results); } }
https://stackoverflow.com/questions/65897330/how-to-query-objects-of-the-same-model-in-a-model-property January 26, 2021 at 03:29PM
没有评论:
发表评论