limiting a join when filtering by an extra field.

I have a query which finds properties based on how far away they are from a certain point and then joins some other tables.
 const sq = db
    .select({
      ...getTableColumns(placeDetailsTable),
      distance: sql<number>`.....`.as("distance"),
    })
    .from(placeDetailsTable)
    .as("subquery");

  const query = await db
    .select()
    .from(sq)
    .where(
      and(lt(sq.distance, maxDistanceInKm), eq(postingsTable.isActive, true)),
    )
    .orderBy(sq.distance)
    .innerJoin(propertiesTable, eq(sq.id, propertiesTable.placeId))
    .innerJoin(
      postingsTable,
      eq(propertiesTable.publicFacingId, postingsTable.propertyPublicId),
    );


I would also like to join a
propertyImages
table but I only want to bring the first 5 of them. I know that this is beautifully easy using relational queries because I can do
{ with: { images: { limit: 5 } } }

However, I am not sure if this filtering based on a calculated field is possible.
extras
is there but then I can't include that in the where clause of the relational query. Maybe I should not join the images table and do a subquery there?
Was this page helpful?