我有两个型号的
Book: id, name, data (json)
Author: id, name
我想用方法author
扩展Book
模型,该方法在查询withRelated
时返回作者。如果我在Book
中有author_id
,那么使用下面的代码段可以很容易地实现这一点
const Book = bookshelf.model('Book', {
tableName: 'books',
author() {
return this.belongsTo('Author', 'author_id', 'id')
}
})
但问题是,author_id
是data
(json类型(的一个属性。我尝试了下面的片段,但它不起作用
const Book = bookshelf.model('Book', {
tableName: 'books',
author() {
return this.belongsTo('Author', `data->>'author_id'`, 'id')
}
})
如果不允许我对原始模型进行任何更改,在这种情况下,我如何获得author
?提前谢谢。
提出了一个有效的解决方案,related
和事件挂钩的组合有点棘手
const Book = bookshelf.model('Book', {
tableName: 'books',
initialize: function() {
this.on('fetched', async function(model) {
model.set('author_id', (model.get('data') || {}).author_id || null)
const author = await model.related('author').fetch()
model.set('author', author)
})
},
author() {
return this.belongsTo('Author')
}
})