在一个原始的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());
},
});
最佳答案
书架没有这个功能,但它提供了一个插件:Virtuals。无需安装任何东西,只需在使用bookshelf.plugin('virtuals')
加载书架后立即加载即可。
然后,您的模型应如下所示:
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());
},
});