Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
98 views
in Technique[技术] by (71.8m points)

javascript - 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, 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);
   }
}
question from:https://stackoverflow.com/questions/65897330/how-to-query-objects-of-the-same-model-in-a-model-property

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...