for (const [references, columns] of referencesArray) { const newQb = qb.with(`cte_${references}`, (wb) => { wb = wb.selectFrom(references).distinct().selectAll(references); for (const column of columns) { wb = wb.innerJoin( tableName, sql.ref(`${tableName}.${column.name}`), sql.ref(`${column.references}.${column.to}`) ); } return wb; }); qb = newQb as any; }