如何在Bookshelf.js中使用groupBy?

6
如何在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);
});

当我尝试对“employee_id”进行“groupBy”时,会出现以下错误。

});

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

2
你究竟想要实现什么? - fingeron
1
除了回答fingeron的评论,您为什么说“我无法在Bookshelf JS中使用groupBy”? 您已经采取了哪些措施来解决问题? 您是否已经查看过文档? 有没有什么文档让您感到困惑或缺失? http://bookshelfjs.org/#Model-instance-fetchPage 中有一个使用groupBy的示例。 - therobinkim
产生错误的查询是什么? - devius
1个回答

6

TL;DR

使用Bookshelf的内置集合操作.fetchAll()后进行自定义的groupBy 或者 使用原始的Knex根据需要生成查询和结果,因为groupBy需要一些SQL聚合定义。这可以是Knex查询结果或Bookshelf对象。

更多内容

Bookshelf并不像它所基于的查询库KnexJS那样是一个查询生成器。Bookshelf是收集来自数据库的行作为对象模型的一种方式。 SQL "groupBy"子句有点针对查询进行自定义,并且Bookshelf本身实现了类似于lodash的方法,例如lodash的groupBy其文档中所述。但是,这是对查询数据进行服务器端分组,而不是使用SQL进行分组。

在使用 Bookshelf 中的 Model 时,你应该在获取数据之前使用 new Model 或者 Model.forge()(如果是多个,则使用 .fetchAll())。你可以通过使用 Model.query查看文档)来开始一个 Knex 查询,但要注意它会返回 Bookshelf 对象。我通常使用 .query(function (qb) {}) 来执行一些自定义的 knex 操作,例如自定义 WHERE 子句或者 qb.orderBy('prop')。由于 groupBy 包含 'many',因此你需要使用 Model.query().fetchAll(),并且要注意查询中的自定义聚合(Bookshelf 可能会处理它,但它不会完全像你定义的模型那样,特别是自定义方法)。直接使用 Knex 也是一个不错的选择。

1
请编辑您的问题,说明您尝试过什么以及出现了什么错误。书架和“groupBy”不像 SQL 的 GROUP BY 语句 - 所以您需要具体说明。 - clay
我编辑了我的问题,当我尝试按employee_id进行“groupBy”时出现错误。 - Apurv Chaudhary
你的代码正在使用 req.body.employee_id 的值,你是不是想用 "employee_id" ?你想要分组的列需要存在于你的表中。 - clay
我使用了“employee_id”,但仍然出现错误“routine:”“errorMissingColumn”。 - Apurv Chaudhary
你的代码在 StudentAttendance 模型中查找 "employee_id"。那么,StudentAttendance 使用了哪些表列?错误很明显:StudentAttendance 模型使用的表中没有名为 "employee_id" 的列。 - clay
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接