【发布时间】: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