如何在Bookshelf js中使用groupBy?

Cha*_*ary 6 node.js bookshelf.js knex.js angular

如何在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);
});
Run Code Online (Sandbox Code Playgroud)

});

当我尝试"groupBy"employee_id时,它会像这样给出错误.

code:"42703"
file:"parse_relation.c"
length:110
line:"3194"
name:"error"
position:"127"
routine:"check_ungrouped_columns_walker"
severity:"ERROR"
Run Code Online (Sandbox Code Playgroud)

cla*_*lay 5

TL; DR

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

更多单词

书架并非完全是查询生成器;不像它是基于查询libray KnexJS的。书架是作为从数据库中收集行作为对象模型的一种方式。一个SQL“GROUPBY”的条款是一种自定义的查询,以及书架本身实现lodash方法,如lodash的groupBy在他们的文档中阐明。但是,这是对查询数据进行服务器端分组,因此未使用SQL进行分组。

Model在书架中使用时,应先使用new Model或,Model.forge()然后再进行提取(或在许多情况下.fetchAll())。您可以通过某种方式Model.query请参阅docs)启动Knex查询,但请注意,这将返回Bookhelf对象。我通常会使用.query(function (qb) {})一些自定义的knex,例如自定义WHERE子句或qb.orderBy('prop')。由于groupBy将包含“许多”,因此您需要Model.query().fetchAll(),并且要知道该查询中的自定义聚合(Bookshelf可能会处理它,但它并不完全类似于您定义的模型,尤其是自定义方法)。直接使用Knex也是一个不错的选择。