Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get 3 data that have the highest value of a column in the table

I am using knex and bookshelf, and my table consists of author, title, content, count, and each data looks like this:

author: 'John Doe',
title: 'aaaaa',
content: 'aaaaaaaa'
count: 54,

I want to retrieve data based on the value of count, and I want to get 4 data that has the highest count value.

If I want to retrieve all data, I am doing like this:

router.get('/', (req, res) => {
   Article.forge().fetchAll().then(article => {
      res.json(article);
   })
}) 

Is there any way that I can do like forge({ count: 3 data that has the highest count value }) or
What should I add the code so that I can achieve this?

like image 403
kay Avatar asked Sep 13 '16 07:09

kay


1 Answers

Combine orderBy with fetchPage

Article
  .orderBy('-count')
  .fetchPage({
    pageSize: 3
  })
  .forge()

This highlights a reason why my team is removing bookshelf and just using basic knex. Unless you are wanting to fetch related models it's simpler to deal without the ORM layer. The knex equivalent knex code is:

  knex('articles')
    .orderBy('count', 'desc')
    .limit(3)

Which is slightly simpler and the resulting rows' properties can be accessed directly, ie rows[0].id rather than rows[0].get('id')

like image 151
Gangstead Avatar answered Jan 01 '23 10:01

Gangstead