![](/img/trans.png)
[英]SELECT specific fields inside the MySQL JSON Column datatype using bookshelf or Knex ORM
[英]BookShelf orm MySQL how to select column1-column2 as alias
在原始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')
加載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());
},
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.