Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

128
Vistas
How to construct conditional AND query to existing query with pg-promise

select statement with dynamic columns for where condition

I need to do exactly what this answer says except my query is:

export async function find_items_based_on_params(category,type,obj) {
const q = 'SELECT * FROM $1 INNER JOIN category ON category.cat_id = $2 WHERE (category.cat_type = $3)'

const res = await sql.query(q, [type,type + '.category_id',category]);
return res;
}

Depending on whether the obj has obj.name obj.color I need to add ' AND table = obj.name '

So if obj parameter was

obj = {
name: 'Brick',
color: 'brown'
}
//Expected query
//SELECT * FROM $1 INNER JOIN category ON category.cat_id = $2 //WHERE (category.cat_type = $3) AND $4:name = $5 AND $6 = $7;

I've tried use the function above and creating my own function (which isn't suggested) but Im struggling to understand how to construct this correctly.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I constructed a custom function to add the values to the query and escaping array. I don't know how safe this is but it works and am awaiting a reply from someone with experience.


export async function find_items_based_on_params(category,type,obj) {
    let res;

    let escaping_array = [];
    let q = 'SELECT * FROM $1:name INNER JOIN category ON category.cat_id = $2:value WHERE category.cat_type = $3';

    escaping_array = [type,type + '.category_id',category];

    res = await        sql.query(add_conditional_and_logic(obj,escaping_array,type,q), escaping_array);

    return res;
}

function add_conditional_and_logic(obj,escaping_array,type,query) {

    Object.keys(obj).map(k => {
        const val = obj[k];
        escaping_array.push(type + '.' + type + '_' + k);
        escaping_array.push(val);
        let len = escaping_array.length;
        query += ` AND $${len -1}:alias = $${len}`;
    });

    return query;
}
//escaping array turns into
//[type,type + '.category_id',category,OBJ.VAL1,OBJ.VAL2]
//q string turns into
//'SELECT * FROM $1:name INNER JOIN category ON category.cat_id = $2:value WHERE category.cat_type = $3 AND $4:alias = $5'
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda