1

I'm trying to output a list of categories that are not related to a particular entry (in order to show a list of services other than the service related to the current entry).

I have this code which lists the category that is related to the current entry:

<ul>
  {% set categories = craft.categories.group('services').relatedTo(entry).all() %}
  {% nav category in categories %}
    <li>{{ category.title }}</li>
  {% endnav %}
</ul>

Is there a way of turning this on its head, so that the other, non-related categories are displayed? Something like a notRelatedTo(entry) parameter?

1

You can grab all ids and exclude them from your query

{% set excludeIds = craft.categories.group('services').relatedTo(entry).ids() %}
{% for category in craft.categories.where(['!=', 'elements.id', excludeIds]).all() %}

If your relation field is in your entry you can do

{% set categories = craft
    .categories
    .section('services')
    .where(['!=', 'elements.id', entry.category.ids()])
    .all()
%}
  • Thanks Robin. I'm still having a problem with this though, as it's now generating a database exception. This is what I have now: <ul> {% set excludeIds = craft.categories.group('services').relatedTo(entry).ids() %} {% for category in craft.categories.where(['!=', 'elements.id', excludeIds]).all() %} <li>{{ category.title }}</li> {% endfor %} </ul> – Eboon Sep 4 '18 at 9:56

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.