【问题标题】:Get count result with knex.js / bookshelf.js使用 knex.js / bookshelf.js 获取计数结果
【发布时间】:2014-03-25 14:54:47
【问题描述】:

我正在尝试使用 knex 进行简单计数(因为它似乎是 to not be supported by bookshelf yet)。以下代码正在运行:

bookshelf.knex('hosts').count('id').then(function(total) {
  res.send({
    meta: {
      total: total[0]['count(`id`)']
    }
  });
});

我觉得很奇怪,我必须做total[0]['count('id')'] 才能得到实际结果。我在这里做事吗?

谢谢!

【问题讨论】:

    标签: bookshelf.js knex.js


    【解决方案1】:

    knex.js 的所有结果都是数组。查询可能会成功,并且只返回 0 个结果。

    此外,您可以直接在列名中为列命名(或count() 调用)。像这样:

      bookshelf.knex('hosts').count('id as CNT').then(function(total) {
        res.send({
          meta: {
            total: total[0].CNT
          }
        });
      });
    

    仍然需要获取第一个元素,但您可以将列作为普通 JSON 属性引用。

    【讨论】:

    • 完美,感谢您的澄清!别名似乎是让我的代码更具可读性的好方法。
    • 谢谢,为什么 knexjs 这么奇怪?返回直接号码似乎很基本。问的太多了吗?
    • (迟到的回复?: ) Knex 建立在 SQL 之上,查询会返回多行结果。因此,在带有count("col") 的 SQL 查询中,将返回一行,通常带有一个名为“count”的列(可以别名)。由于 Knex 是围绕 SQL 构建的,因此查询总是返回一个对象数组(行),并带有与列匹配的属性。可以为.count() 或其他人创建一个特殊情况以返回单个值,但实际上它们只是聚合器,您可以在同一个查询中拥有一些(甚至.groupBy() 不同的列,在这种情况下您将拥有许多行作为组,每个都有自己的计数)。
    • @clay 如果我想计算 where column1 = 'some value',该怎么写?
    • 对于任何“特别”的东西,你都可以使用knex.raw,比如knex.raw('sum(case when "column1" = \'someValue\' then 1 else 0 end) as "total"')
    【解决方案2】:

    虽然 knex 确实将结果作为数组返回,但它也有一个返回第一个结果的方法,该结果将是一个对象,而不是一个数组。无需依赖 [0] 或任何东西来访问数组中的计数,直接获取计数非常简单。对于您的示例,更清洁的解决方案可能是:

    bookshelf
      .knex("hosts")
      .count("id")
      .first()
      .then(function(total) {
        res.send({
          meta: {
            total: total.count
          }
        });
      });
    

    【讨论】:

      【解决方案3】:

      这似乎可以正常工作并且更简单一些

      knex('Quotes').count('quoteBody')
          .then((res)=>{
              //console.log("rows "+JSON.stringify(res))        
              console.log("rowspl2 "+res[0]['count(`quoteBody`)'])
          })
          .catch((err)=>{
              console.log("err "+err)
          })
      

      或像这样尝试

          knex('Quotes').count('quoteBody', {as: 'rows'})
              .then((res)=>{
                 // console.log("rows "+JSON.stringify(res))
                  console.log("rowsp "+res[0]['rows'])
              })
              .catch((err)=>{
                  console.log("err "+err)
              })
      

      【讨论】:

        【解决方案4】:

        节点js代码

        let result = await knex.count("id").from('events').first();
        if (result) {
        console.log(result.count);
        }  
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-03-06
          • 2014-09-22
          • 1970-01-01
          • 2014-01-17
          • 1970-01-01
          • 2017-06-16
          • 2014-02-19
          • 1970-01-01
          相关资源
          最近更新 更多