BookShelf orm MySQL 如何 select column1-column2 作为别名
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());
},
});
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());
},
});
在原始 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());
},
});
Bookshelf 没有此功能,但它为此提供了一个插件: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());
},
});