Tengo una tabla que estoy consultando usando findAndCountAll()
Básicamente lo estoy usando para paginación/pedido usando las propiedades de order , limit e index . Algo simple como esto:
exports.getApplications = async(req, res, next) => { const findOne = req.query.indexId; const index = req.query.index || 0; const limit = req.query.limit || 10; const orderField = req.query.orderField || 'createdAt'; const orderDirection = req.query.orderDirection || 'DESC'; const order = [ orderField, orderDirection ]; const applications = await Application.findAndCountAll({ order: [order], limit: parseInt(limit, 10), offset: parseInt(index) // ... } } Pero también me gustaría poder especificar un ID de findOne indexId y que esa entrada única aparezca antes de la lista paginada/ordenada (* edición : la fila puede o no estar incluida en la lista paginada que se devuelve )
¿Es eso posible usando findAndCountAll ? ¿O tendría que ejecutar una consulta separada usando findByPk() , reducir el límite en 1, luego cambiar la entrada al frente de la matriz de resultados?
Gracias,
Mella
*Editar - Implementación en caso de que alguien esté interesado. Ahora solo queda hacer que las consultas se ejecuten en paralelo :)
try { // Find a specific row to highlight if needed if(findOne) { topRow = await Application.findByPk(findOne, { include: [...], }); } const applications = await Application.findAndCountAll({ include: [...], order: [order], limit: parseInt(limit, 10), offset: parseInt(index) }); // If there's a row to be highlighted if(topRow) { const visible = applications.rows.filter(application => application.id === topRow.id); const index = applications.rows.findIndex(application => application.id === topRow.id); // 1 too many results in the array if(applications.rows.length + 1 > limit) { // If the row appears in the array to be returned, remove it if(visible) { applications.rows.splice(index, 1); } else { // Remove the last element instead applications.rows.pop(); } } else { if(visible) applications.rows.splice(index, 1); } // Add the highlighted topRow to the array applications.rows.unshift(topRow) }Intente hacer esto, asumiendo que su valor findOne es seguro de usar:
order: [ [sequelize.literal(`id = ${findOne}`), 'DESC'], [orderField, orderDirection] ] Esto devolverá true para la fila que desea, false para los demás, por lo que primero lo ordenará en la parte superior y luego continuará con el resto del orden.