RelatedTo query with length criteria I am trying to get results from a relatedTo query, but only if there are more than say 1 results. Right now I am using two queries to achieve this, like so:

{% set authors = craft.entries({
    section: 'authors',
    with: [
        'authorImage',
    ],
    limit: 18,
    order: 'authorSurname asc'
}) %}
{% for author in authors %}
    {% set relatedEntries = craft.entries.section('articles').sponsoredAuthor('= 0').relatedTo(author) %}
    {% if relatedEntries|length &gt; 1 %} ... {% endif %}
{% endfor %}


But this messes up pagination (amongst other things) because the loop will iterate no mater if the related entries have more than 1 result. So I was wondering if it is possible (without using a custom query) to have the same result as a single query, so that the results match the number of the items in the loop and pagination does not break. Something like:

authors = craft.entries.section('authors').relatedTo('articles where articles results &gt; 1)


or something like that. Is it possible?

Thanks!
The only way I can think to do this is with a plugin that tracks the relation count, storing it as a custom field.

First create a new Number custom field called “Total Articles” (handle: totalArticles). Assign it to your Authors field layout.

Then create a new plugin. Put this in the primary plugin class’ init() method:

craft()-&gt;on('entries.saveEntry', function(Event $event) {
    /** @var EntryModel $entry */
    $entry = $event-&gt;params['entry'];

    if ($entry-&gt;getSection()-&gt;handle === 'articles') {
        // Update author relation counts
        foreach ($entry-&gt;relatedAuthor as $author) {
            $criteria = craft()-&gt;elements-&gt;getCriteria(ElementType::Entry);
            $criteria-&gt;section = 'articles';
            $criteria-&gt;relatedTo(array(
                'targetElement' =&gt; $author,
                'field' =&gt; 'relatedAuthor'
            ));
            $totalArticles = $criteria-&gt;total();

            craft()-&gt;db-&gt;createCommand()-&gt;update('content',
                array('field_totalArticles' =&gt; $totalArticles),
                array('elementId' =&gt; $author-&gt;id));
        }
});


Finally, from your template, you can fetch only the authors that have at least 2 articles like so:

{% set authors = craft.entries({
    section: 'authors',
    totalArticles: '&gt;= 2',
    with: [
        'authorImage',
    ],
    limit: 18,
    order: 'authorSurname asc'
}) %}