【问题标题】:How to query objects of the same model in a model property如何在模型属性中查询同一模型的对象
【发布时间】:2021-01-26 07:29:05
【问题描述】:

我正在使用 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);
   }
}

【问题讨论】:

    标签: javascript node.js psql objection.js


    【解决方案1】:

    你可以尝试使用afterFind钩子:

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

    【讨论】:

    • 不起作用,customProperty 未定义,我需要在 virtualAttribute 中定义它吗?我尝试创建一个类似于 SomeModelHelper 的辅助模型,它与 SomeModel 相同,并在有效的查询中使用它,但这是最好的方法吗?我注意到使用 async $afterFind 而不是静态 async $afterFind 可以工作,并结合我提到的辅助模型
    • $afterFind 是有道理的。但是创建辅助模型应该不是必需的。引用SomeModel 不起作用? (更新了响应)。此外,then/catch 语法不应与 async/await 混合使用。
    • 不,我假设它只是进入了一个无限循环,所以它只是失败了
    • 感谢您指出,仅使用 SomeModel.query().then() 而不使用 async/await 就可以使其工作,有趣的是,您的答案进入了无限循环
    • 欢迎你 :) 如果你还想在不使用 helper 的情况下尝试一下,我想你可以使用this.query().where('property1', this.property1)(或this.$query().where('property1', this.property1),我不熟悉 v2 新方法)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-13
    • 1970-01-01
    • 2014-04-20
    • 1970-01-01
    • 2017-04-18
    • 2018-08-10
    相关资源
    最近更新 更多