1

I have a channel with Authors. Not all of them are used right now, so I'm trying to construct a query that will fetch all Authors are are related to some article.

This is what I've tried so far:

{% set allAuthors = craft.entries
    .section('authors')
    .relatedTo('not ' ~ null)
    .limit(null)
    .all()
%}

This yielded exactly nothing. Same with having 'not null' as a string on line 3 above.

I've tried looking over the documentation here, but was unable to find information on this scenario.

This is the (extremely) dirty way of accomplishing this, but pagination becomes nearly impossible:

{% set allAuthors = craft.entries
    .section('authors')
    .limit(null)
    .all()
%}
<ul>
{% for author in allAuthors %}
    <li>
    {% set articlesByThisAuthor = craft.entries
        .section('articles')
        .relatedTo(author)
        .all()
    %}
    {% if articlesByThisAuthor|length > 0 %}
        {{ author.title }}: {{ articlesByThisAuthor|length }}
    {% endif %}
    </li>
{% endfor %}

Perhaps I'm approaching this all wrong?

1 Answer 1

2

If the authors are the source of the relationship, you can simply use the :notempty: syntax on the field with the relation. But I'm going to assume the authors are the target of the relationship, since that probably makes more sense.

In this case, you can solve this with a custom where condition or join, but that's a bit more involved. A simpler solution is to pass a query that selects all applicable entries to the relatedTo parameter.

{% set articles = craft.entries().section('article') %}
{% set authors = craft.entries()
    .section('authors')
    .relatedTo(articles)
    .all()
%}
1
  • 1
    Oh, cool. I did not know that I could relate to an entire section like that. Thanks! Commented Mar 17, 2022 at 14:12

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.