[英]Bookshelf.js relation with foreign key from a property in json
I have 2 models我有 2 个模型
Book: id, name, data (json)
Author: id, name
I want to extend Book
model with method author
which return the author when query withRelated
.我想使用方法author
扩展Book
model ,该方法在查询withRelated
时返回作者。 This could be easy to achieve with below snippet, provided that I have author_id
in Book
如果我在Book
中有author_id
,这可以通过以下代码段轻松实现
const Book = bookshelf.model('Book', {
tableName: 'books',
author() {
return this.belongsTo('Author', 'author_id', 'id')
}
})
But the problem is, author_id
is a property of data
(which is json type).但问题是, author_id
是data
的一个属性(它是 json 类型)。 I tried the snippet below but it not worked我尝试了下面的代码段,但没有奏效
const Book = bookshelf.model('Book', {
tableName: 'books',
author() {
return this.belongsTo('Author', `data->>'author_id'`, 'id')
}
})
If I am not allowed to have any changes in the origin models, how could I get author
in this case?如果我不允许对原始模型进行任何更改,在这种情况下我怎么能得到author
? Thanks in advance.提前致谢。
Came up with a solution that worked, a little bit tricky combination of related
and event hook想出了一个可行的解决方案, 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')
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.