如何在一个模型中查询同一个模型的对象属性

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

我正在使用 objection.js,并且我有这个模型,并且想要获得与当前实例共享相同 属性 值的其他对象实例,例如

Example of model structure:

SomeModel {
  property1: 'string',
}


Objection.js: 

class SomeModel extends Model{
   static get tableName() {
       return 'some_model'
   }
}

并且我想创建一个自定义 属性 来为共享相同值的其他人过滤模型,以便我可以获得 modelInstance.customProperty 并且它 returns 过滤列表对象。最好的方法是什么?我尝试使用 virtualAttribute 无济于事,因为查询应该在异步函数中,并且虚拟属性不支持

class SomeModel extends Model{
   static get tableName() {
       return 'some_model'
   }

   static get virtualAttributes() {
       return ['customProperty'];
   }

   async customProperty() {
      return SomeModel.query().where('property1', this.property1)
   }
}

我知道这种方法是错误的,但我希望你知道我在寻找什么

编辑: 所以我尝试使用这种方法,但我不确定它是否是最好的方法

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

感谢@rashomon 的评论,我设法用

解决了它
class SomeModel extends Model{
   static get tableName() {
       return 'some_model';
   }

   $afterFind(args) {
       SomeModel.query()
       .where('property1', this.property1)
       .then(results => this.customProperty = results);
   }
}

您可以尝试使用 afterFind 钩子:

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