'How can I get the value from a Knex query using max?
I have a very simple Knex query against a MySQL table to find the maximum value of the id column:
const maxId = await knex('some_table').max('id').first()
But this returns a TextRow object with a single, oddly named property. From a console.log:
TextRow { 'max(`id`)': 99 }
Is there an easy way for me to get the value, or do I have to use object property notation like this:
const idValue = maxId['max(`id`)']
Solution 1:[1]
It appears the easiest answer is to alias the result, as in the second example shown here:
const maxIdQuery = await knex('some_table').max('id as maxId').first()
console.log(maxIdQuery.maxId) // shows the value
Alternate syntax:
const maxIdQuery = await knex('some_table').max('id', { as: 'max_id' })
console.log(maxIdQuery[0]['max_id'])
Hope this helps someone in the future.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
