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

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

<p>Then create a new <a href="https://craftcms.com/docs/plugins/introduction" rel="nofollow noreferrer">plugin</a>. Put this in the primary plugin class’ <code>init()</code> method:</p>

<pre class="lang-php prettyprint-override"><code>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));
        }
});
</code></pre>

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

<pre class="lang-twig prettyprint-override"><code>{% set authors = craft.entries({
    section: 'authors',
    totalArticles: '&gt;= 2',
    with: [
        'authorImage',
    ],
    limit: 18,
    order: 'authorSurname asc'
}) %}
</code></pre>

CC BY-SA 3.0
2017-07-12T11:30:51.377Z
Thanks Brandon! It works, just had to change $criteria->relatedTo = array(...); But now I have to re-save all entries in order to get the proper counts. Is there a (mass) way to do this, without updating the "updated date"? Thanks!
Evangelos
CC BY-SA 3.0
2017-07-12T16:36:31.890Z
@epap If you resave the section, all the entries will get resaved (even if you don't change any settings). Although I think that the dateUpdated columns will get updated, too.
Brandon Kelly
CC BY-SA 3.0
2017-07-18T19:35:10.513Z
What if I want to remove an author from an article. How to I update the totalArticles textfield. I cannot find an event that will help me grab the previous author (related entry) before I replace it (or remove it) - How do I approach this?
Evangelos
CC BY-SA 3.0
2017-06-28T13:48:09.727Z
2017-06-28T13:48:09.727Z
Brandon Kelly
<p>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:</p>

<pre><code>{% 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 %}
</code></pre>

<p>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:</p>

<pre><code>authors = craft.entries.section('authors').relatedTo('articles where articles results &gt; 1)
</code></pre>

<p>or something like that. Is it possible?</p>

<p>Thanks!</p>

CC BY-SA 3.0
2017-06-28T05:33:52.680Z
Is the relationship field stored on the Authors or the Entries? What is its handle?
Brandon Kelly
CC BY-SA 3.0
2017-06-28T06:56:55.803Z
Hi Brandon, the relationship field is stored on the entries (relatedAuthor). Tried something like that `relatedTo({
    sourceElement: craft.entries.section('articles').sponsoredAuthor('= 1'),
    field: 'relatedAuthor'` but still not sure how to get the length / results from Articles
Evangelos
CC BY-SA 3.0
2017-06-28T11:02:45.327Z
OK and to clarify, you want to loop through all the authors that have at least 2 entries related to them?
Brandon Kelly
CC BY-SA 3.0
2017-06-28T12:37:40.503Z
Exactly! But on a single query, otherwise if I have to add a condition whether or not to show something (relatedEntries > 1) it messes up the pagination. I am also looking for a sponsoredAuthor (a field on articles) to be off (0) - here is our demo http://www.epixeiro.gr/authors, you can see many authors with 0 or 1 entries - I do not want to show these, but I still want the pagination (limit + offset entries) to work properly! Thanks.
Evangelos
<relations><queries><relatedto><query>
RelatedTo query with length criteria
# RelatedTo query with length criteria

(Asked by: username_0 on 2017-06-27)

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 > 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 > 1)

or something like that. Is it possible?
Thanks!

**Tags:** relations, queries, relatedto, query

> **Comments:**
> **username_1**: Is the relationship field stored on the Authors or the Entries? What is its handle?  
> **username_0**: Hi Brandon, the relationship field is stored on the entries (relatedAuthor). Tried something like that `relatedTo({     sourceElement: craft.entries.section('articles').sponsoredAuthor('= 1'),     field: 'relatedAuthor'` but still not sure how to get the length / results from Articles  
> **username_1**: OK and to clarify, you want to loop through all the authors that have at least 2 entries related to them?  
> **username_0**: Exactly! But on a single query, otherwise if I have to add a condition whether or not to show something (relatedEntries > 1) it messes up the pagination. I am also looking for a sponsoredAuthor (a field on articles) to be off (0) - here is our demo http://www.epixeiro.gr/authors, you can see many authors with 0 or 1 entries - I do not want to show these, but I still want the pagination (limit + offset entries) to work properly! Thanks.  

---

## 1 answers

### Answer by username_1 on 2017-06-28. Score: 1 | Accepted answer

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()->on('entries.saveEntry', function(Event $event) {
    /** @var EntryModel $entry */
    $entry = $event->params['entry'];

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

            craft()->db->createCommand()->update('content',
                array('field_totalArticles' => $totalArticles),
                array('elementId' => $author->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: '>= 2',
    with: [
        'authorImage',
    ],
    limit: 18,
    order: 'authorSurname asc'
}) %}

> **Comments:**
> **username_0**: Thanks Brandon! It works, just had to change $criteria->relatedTo = array(...); But now I have to re-save all entries in order to get the proper counts. Is there a (mass) way to do this, without updating the "updated date"? Thanks!  
> **username_1**: @epap If you resave the section, all the entries will get resaved (even if you don't change any settings). Although I think that the dateUpdated columns will get updated, too.  
> **username_0**: What if I want to remove an author from an article. How to I update the totalArticles textfield. I cannot find an event that will help me grab the previous author (related entry) before I replace it (or remove it) - How do I approach this?  

---

