define where query outside

I dont understand why this code works :
const whereQuery = exists(
    db
      .select({ id: sql`1` })
      .from(productsOrderTable)
      .where(
        and(
          eq(productsOrderTable.orderId, ordersTable.id),
          ilike(productsOrderTable.name, "%" + query + "%"),
        ),
      ),
  )

  const [orders, ordersLength] = await Promise.all([
    db.query.ordersTable.findMany({
      limit: ordersByPage,
      offset: (page - 1) * ordersByPage,
      with: {
        products: true,
        user: {
          columns: {
            password: false,
          },
        },
      },
      where: (ordersTable) => exists(
        db
          .select({ id: sql`1` })
          .from(productsOrderTable)
          .where(
            and(
              eq(productsOrderTable.orderId, ordersTable.id),
              ilike(productsOrderTable.name, "%" + query + "%"),
            ),
          ),
      ), ### only changed this part of the code
      orderBy: (ordersTable, { desc }) => desc(ordersTable.date),
    }),
    db
      .select({ count: count() })
      .from(ordersTable)
      .where(whereQuery),
  ]);


But not this one :

const whereQuery = exists(
    db
      .select({ id: sql`1` })
      .from(productsOrderTable)
      .where(
        and(
          eq(productsOrderTable.orderId, ordersTable.id),
          ilike(productsOrderTable.name, "%" + query + "%"),
        ),
      ),
  )

  const [orders, ordersLength] = await Promise.all([
    db.query.ordersTable.findMany({
      limit: ordersByPage,
      offset: (page - 1) * ordersByPage,
      with: {
        products: true,
        user: {
          columns: {
            password: false,
          },
        },
      },
      where: whereQuery, ### only changed this part of the code
      orderBy: (ordersTable, { desc }) => desc(ordersTable.date),
    }),
    db
      .select({ count: count() })
      .from(ordersTable)
      .where(whereQuery),
  ]);
Was this page helpful?