繁体   English   中英

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

[英]How to query objects of the same model in a model property

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

Example of model structure:

SomeModel {
  property1: 'string',
}


Objection.js: 

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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