In order to get the parent post, you would use the wp_get_post_parent_id()
function.
So in your foreach
loop, you would want to add something like:
$parent = wp_get_post_parent_id( $attachment->ID );
<a href="https://wordpress.stackexchange.com/questions/260459/<?php esc_url( the_permalink( $parent ) ) ?>">
// Rest of your HTML
</a>