【问题标题】:How to use groupBy in Bookshelf js?如何在 Bookshelf js 中使用 groupBy?
【发布时间】:2018-01-04 08:11:31
【问题描述】:

如何在Bookshelf JS中使用groupBy,这是我的Controller代码。

router.route('/fetchStudentAttendance')
.post(function(req, res) {
 StudentAttendance
  .query(function (qb){
    qb.where('date', '>=', req.body.date);
    qb.groupBy("students_id");
  })
.where({'class_id': req.body.class_id, 'section_id': req.body.section_id})
.fetchAll({ withRelated: [{'StudentRef':function(qb) {qb.column('id', 'first_name', 'middle_name', 'last_name')}}]})
.then(studentAttendance => {
  let content = {
    data: studentAttendance,
    success: true,
    message: 'Record Not Found',
  };
  return res.send(content);
})
.catch(error => {
  let content = {
      data: error,
      success: false,
      message: 'Error while fetching Student Attendance.',
    };
  return res.send(content);
});

});

当我尝试“groupBy”employee_id 时,它会给出这样的错误。

code:"42703"
file:"parse_relation.c"
length:110
line:"3194"
name:"error"
position:"127"
routine:"check_ungrouped_columns_walker"
severity:"ERROR"

【问题讨论】:

  • 你到底想要达到什么目的?
  • 除了回复fingeron的评论,你说I am not able to use groupBy in Bookshelf JS的理由是什么?到目前为止你做了什么来解决你的问题?你看过文档了吗?您发现文档令人困惑/缺乏什么? bookshelfjs.org/#Model-instance-fetchPage 有一个 groupBy 正在使用的示例。
  • 产生错误的查询是什么?

标签: node.js angular knex.js bookshelf.js


【解决方案1】:

TL;DR

.fetchAll()之后使用Bookshelf的built-in Collection manipulation做自定义groupBy 或者 根据需要使用原始 Knex 生成查询和结果,因为 groupBy 将需要一些 SQL 聚合定义。这可以是 Knex 查询结果或 Bookshelf 对象。

更多单词

Bookshelf 不完全是一个查询生成器;不像查询库KnexJS 它是由它构建的。 Bookshelf 是作为对象模型从数据库中收集行的一种方式。 SQL "groupBy" 子句是对查询的一种自定义,Bookshelf 本身实现了 lodash 方法,例如 lodash 的 groupBystated in their docs。但是,这是对查询数据的服务器端分组,它没有使用 SQL 来这样做。

在 Bookshelf 中使用Model 时,应在获取之前使用new ModelModel.forge()(或者如果有很多,则使用.fetchAll())。您可以通过使用Model.query (see docs) 以某种方式启动 Knex 查询,但请注意这将返回 Bookshelf 对象。我通常使用.query(function (qb) {}) 来做一些自定义knex,例如自定义WHERE 子句或qb.orderBy('prop')。由于groupBy 将包含“许多”,因此您需要Model.query().fetchAll(),并注意该查询中的自定义聚合(Bookshelf 可能会处理它,但它不会与您定义的模型完全相同,尤其是使用自定义方法时)。直接使用 Knex 可能也是一个不错的选择。

【讨论】:

  • 请根据您的尝试和遇到的错误来编辑您的问题。 Bookshelf 和“groupBy”不像 SQL GROUP BY 语句 - 所以你必须具体。
  • 我编辑了我的问题,当我尝试“groupBy”employee_id 时出现错误。
  • 您的代码使用的是req.body.employee_id 的值,您的意思是“employee_id”吗?您要分组的列需要存在于您的表格中。
  • 我使用“employee_id”,但仍然收到错误“routine:”“errorMissingColumn”“”
  • 您的代码正在StudentAttendance 模型中寻找“employee_id”。 StudentAttendance 使用表的哪些列?错误很明显:StudentAttendance 模型中使用的表没有名为“employee_id”的列。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-27
  • 1970-01-01
  • 1970-01-01
  • 2020-03-15
  • 1970-01-01
  • 2017-01-05
  • 1970-01-01
相关资源
最近更新 更多