4

Given a list of assets, for each asset, how do I display a list of entries that relate to this asset? So, for instance, if asset A is selected as asset in entries 1 and 2, I want a list to be displayed like this:

  • Asset A:
    • Used in entry 1
    • Used in entry 2
  • Asset B:
    • Used in ... etc.

With this ...

{% set content = craft.entries.section('content').find() %}
{% set usedFotos = craft.assets.relatedTo(content).find() | group('id') %}

... I can see if certain assets are used, but now I want to see what entr(y/ies) they belong to.

3
  • Paul, did the answer I provided help you with your problem?
    – carlcs
    Aug 21 '14 at 16:13
  • Didn't have a chance to try yet, will do tonight. Was hoping for a 'one-query solution' ;)
    – Paul
    Aug 21 '14 at 16:16
  • Yeah I also hoped to find a solution with less DB queries, but I don't think it's possible.
    – carlcs
    Aug 21 '14 at 16:21
5

You probably have to query a new ElementCriteriaModel for each asset in your loop and use the relatedTo parameter to filter the relevant "content" entries.

You could use the targetElement property with the relatedTo parameter to be more spezific on that relation. But you should be fine using the element property or the short syntax relatedTo(element), if you don't do any (reverse) relations (e.g. with an entries field as an asset meta field).

Tested this on an install with 400 images and yes, you want to wrap it in cache tags!

{% set content = craft.entries.section('content').find() %}
{% set usedFotos = craft.assets.relatedTo(content).order('filename').find() %}

{# Loop throught the array of assets #}
{% for usedFoto in usedFotos %}

    <h2>{{ usedFoto.filename }}</h2>
    <ul>

        {# Loop throught entries related to this asset #}
        {% for entry in craft.entries.relatedTo(usedFoto).order('title') %}
            <li>{{ entry.title }}</li>
        {% endfor %}

    </ul>

{% endfor %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.