How can I limit the output of assets randomly if an asset exists? How can I limit the output of assets based on this criteria?


search all entries randomly in section "homes" for only entries with at least one asset image
limit those results to 8 random assets


I tried this but it does not always show exactly 8 asset images as the random is called first:

{% set assets = craft.assets.limit(null) %}

{% for homesEntry in craft.entries.section('homes').limit(8).order('RAND()') %}
    {% if homesEntry.homeImages|length %}
        {% set asset = homesEntry.homeImages.first() %}

        {% if asset %}
            &lt;a href="{{ homesEntry.url }}"&gt;&lt;img src="{{ asset.url('homeImages') }}" alt="{{ asset.title }}"&gt;&lt;/a&gt;
        {% endif %}
    {% endif %}
{% endfor %}


Any help is appreciated.
This is how you do it in case anyone is looking for this.

{% set assets = craft.assets.limit(null) %}

{% set randomEntry = craft.entries.section('homes').order('RAND()').relatedTo({
    targetElement: assets,
    field: 'homeImages'
}) %}

{% for homesEntry in randomEntry.limit(6) %}
    {% set asset = homesEntry.homeImages.first() %}

    {% if asset %}
        &lt;a href="{{ homesEntry.url }}"&gt;&lt;img src="{{ asset.url('galleryImages') }}" alt="{{ asset.title }}"&gt;&lt;/a&gt;
    {% endif %}
{% endfor %}