2

I've got a few categories set up with a few child categories for each. Each one has assets (PDFs) assigned to them, by going into the assets, double clicking, and setting the category field there. So for example:

Category 1
-- asset 1
- Sub Category 1
-- asset 2
-- asset 3

Category 2
-- asset 4
- Sub Category 1
-- asset 5
-- asset 6

But when I'm looping through the related assets, using:

 {% for category in craft.categories.group('categoryGroup').level(1) %}
    {% set resources = craft.assets.relatedTo(category).find() %}
      {% for resource in resources %}
        {{ resources.title }}
      {% endfor %}
 {% endfor %

I get:

Category 1
- asset 1
- asset 2
- asset 3
- Sub Category 1
-- asset 1
-- asset 2
-- asset 3

Category 2
- asset 4
- asset 5
- asset 6
- Sub Category 1
-- asset 4
-- asset 5
-- asset 6

Which logically makes sense, that it's returning all assets related to the children categories, since those are also related to the parent. But how can I exclude them from the loop, so I only get back the assets that are directly related?

1 Answer 1

1

Rather than preparing multiple queries - you can execute the Query in your field value

{% for category in craft.categories.group('categoryGroup').level(1).find() %}
    {% for resource in category.fieldHandle.find() %}
        {{ resources.title }}
    {% endfor %}
{% endfor %
4
  • not following. i get that it cuts down on queries but it doesn't solve my problem...
    – strandall
    Commented Aug 3, 2018 at 14:58
  • It should since you'll only fetch the related assets and not all of the hierarchy Commented Aug 3, 2018 at 15:10
  • hm, okay. the categories only have title fields, and it's throwing an error about invoking "find" on a string
    – strandall
    Commented Aug 3, 2018 at 15:19
  • Okay, then your initial code wasn't really good since you want to avoid the syntax you used in that case. However, categories don't work that way. You either need to create a custom field or use entries for that purpose since categories will relate all the way up to all hierarchy levels. When you relate a child, the parent will be related as well Commented Aug 3, 2018 at 15:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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