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

问题描述

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

Example of model structure:

SomeModel {
  property1: 'string',}


Objection.js: 

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

我想创建一个自定义属性,为共享相同值的其他人过滤模型,以便我可以获取 modelInstance.customProperty 并返回过滤对象的列表。最好的方法是什么?我试过使用 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)
   }
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...