简体   繁体   中英

How to query objects of the same model in a model property

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, eg

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);
   }
}

You can try using afterFind hook:

class SomeModel extends Model {
   static get tableName() {
       return 'some_model'
   }
   async $afterFind(args) {
       this.customProperty = await this.query()
         .where('property1', this.property1)
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM