Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

122
Views
Concept involved in using nested Knex

In my programming in Node.JS I made some code that worked, but I want to understand the concept of how it works.

In the code in question I use knex to retrieve information from a MySQL database. I import the knex module for that:

const config = {...}
const knex = require('knex')(config)

So far nothing new, only this time I needed to do a nested query and it was the first time. In this case, I consulted the sales data and then the sale items. I did it as follows:

const getSales = async () => {
    await knex("tbl_vendas")
        .select(knex.raw("tbl_vendas.id_vendas, tbl_vendedores.nome AS vendedor, " +
            "tbl_clientes.nome_razaosocial AS cliente, tbl_vendas.data, tbl_vendas.hora, " +
            "tbl_vendas.cupom, tbl_vendas.total"))
        .leftOuterJoin("tbl_vendedores", "tbl_vendedores.id_vendedores", "tbl_vendas.id_vendedores")
        .leftOuterJoin("tbl_clientes", "tbl_clientes.id_clientes", "tbl_vendas.id_clientes")
        .then(sales => {
            const rows = sales.map(sale => {
                return knex("tbl_vendas_itens")
                    .select("tbl_vendas_itens.id_vendas_itens AS id_item", "tbl_produtos.descricao",
                        "tbl_vendas_itens.qtde", "tbl_vendas_itens.vl_unitario", "tbl_vendas_itens.desconto",
                        "tbl_vendas_itens.vl_total")
                    .leftOuterJoin("tbl_produtos", "tbl_vendas_itens.id_produtos", "tbl_produtos.id_produtos")
                    .where("tbl_vendas_itens.id_vendas", "=", sale.id_vendas)
                    .then(sales_items => {
                        const newRow = { ...sale, itens: [...sales_items] }
                        return newRow
                    })
            })
            return Promise.all(rows)
        })
        .then(console.log);
}

Writing this code was pretty intuitive and it worked, but then I was amazed that I used the knex constant twice, one inside the other, and it didn't hurt.

I ran a console.log(typeof(knex)) to find out what it was and it returned that it is a function.

Could someone explain the theory behind the use of knex inside the other and help me understand why it is okay to do this?

about 4 years ago · Santiago Gelvez
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!