【问题标题】:BookShelf orm MySQL how to select column1-column2 as aliasBookShelf orm MySQL如何选择column1-column2作为别名
【发布时间】:2017-04-20 17:33:37
【问题描述】:

在一个原始的 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());
  },
});

【问题讨论】:

    标签: mysql knex.js bookshelf.js


    【解决方案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());
      },
    });
    

    【讨论】:

    • 能否详细说明如何“加载书架后立即加载”?我有这样的书架const Bookshelf = require('bookshelf')(knex); Bookshelf.plugin('virtuals'); module.exports = Bookshelf; 在一个单独的文件中,我导入了配置。 const bookshelf = require('../knex_config.js'); 但我仍然遇到同样的错误。
    • 你做对了。这正是我所说的“马上”的意思。你遇到了什么错误?
    • 我认为您仍然无法选择 net_sales 作为列。您可以使用 model.get('net_sales'),但不能使用列标题。
    • 是的,可能是fetch() 对其columns 参数的限制。但更有可能的是可以在虚拟插件上改进的东西。我稍后再看看。
    猜你喜欢
    • 2021-01-30
    • 1970-01-01
    • 2021-06-06
    • 1970-01-01
    • 1970-01-01
    • 2016-01-01
    • 2015-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多