在原始的MySQL查询中,我有类似的东西:
Select total_sales - over_head_costs As net_sales from departments;
如何通过BookShelf / knex查询实现相同的功能?理想情况下不使用knex.raw。
我的尝试包括:
let Department = bookshelf.Model.extend({
tableName: 'departments',
idAttribute: 'department_id',
},{
getDepartments: function(){
return this.fetchAll({columns: ['department_id', 'department_name', 'over_head_costs', 'total_sales - over_head_costs AS net_sales']})
.then(models=>models.toJSON());
},
});
答案 0 :(得分:1)
Bookshelf没有此功能,但它带来了一个插件:Virtuals
。无需安装任何内容,只需在使用bookshelf.plugin('virtuals')
加载Bookshelf后立即加载。
您的模型应该如下所示:
const Department = bookshelf.Model.extend({
tableName: 'departments',
idAttribute: 'department_id',
virtuals: {
net_sales: function() {
return this.get('total_sales') - this.get('over_head_costs');
}
}
},{
getDepartments: function(){
return this.fetchAll({columns: ['department_id', 'department_name', 'over_head_costs', 'net_sales']})
.then(models=>models.toJSON());
},
});