Modified select() on an existing query example

Hey, I would like to reuse first query with some left joins etc. to obtain results count with second query

I found some posts, and it seems its possible, but cant get it working.

I just need to alternate select() to other fields, more precisely to a simple sql count expression.

// random query with left join
    const query = db
      .select({
        id: documentLine.id,
        documentId: documentLine.documentId,
        productVariant: {
          id: productVariant.id,
          fullName: productVariant.fullName,
        },
      })
      .from(documentLine)
      .leftJoin(
        productVariant,
        eq(productVariant.id, documentLine.productVariantId)
      )
// it applies fileters, ordering, pagination
    let paginatedResults = await getPaginatedResponse(query, filters, ordering, limit, offset)

// need to copy query with all filters and more important with joins
    let countQuery = query.$dynamic().where(and(...filters))

// sample attempt to alternate select
    let count = countQuery._.selectedFields({ count: sql<string>`count(*)` })



helpIs there a way to modify the select() on an existing query ?

https://github.com/drizzle-team/drizzle-orm/issues/561
Was this page helpful?