<p>There’s no way to tell the <code>relatedTo</code> param to only factor in the first <em>X</em> relations per source element (the first 5 tags per user, in this case).</p>

<p>I can think of two ways you could accomplish this:</p>

<p><strong>Option 1: Use two Specialism fields</strong></p>

<p>Replace your “Specialism” Tags field with two <a href="http://buildwithcraft.com/docs/categories-fields" rel="nofollow">Categories fields</a> – “Primary Specialism” and “Secondary Specialism”. Limit “Primary” to 5 categories, so no one can ever enter more than 5 specialties in there, and they can list any additional specialties  in the “Secondary” field.</p>

<p>Then from your template, you can limit the search query to only factor in the “Primary” field:</p>

<pre><code>{% set results = craft.users({
    group: 'verified',
    relatedTo: {
        targetElement: craft.categories({
            group: 'specialisms',
            search: query
        }),
        field: 'primarySpecialism'
    }
%}
</code></pre>

<p>This method will get more complicated if you do start allowing premium members to be found from both fields down the road; you would need to split it up into two separate user queries – first for the premium members, and then again for the normal members.</p>

<p><strong>Option 2: Automatically store the searchable specialisms in a separate, hidden field</strong></p>

<p>Install the excellent <a href="https://github.com/aelvan/Preparse-Field-Craft" rel="nofollow">Preparse</a> plugin, and create a new Preparse field called “Searchable Specialisms” with the following Twig code:</p>

<pre><code>{% spaceless %}
    {% for tag in user.specialismTags.limit(5) %}
        {{ tag.title }}
    {% endfor %}
{% endspaceless %}
</code></pre>

<p>(Disable the “Show Field” setting so this field doesn’t show up on user profile pages. <code>{% spaceless %}</code> is required to <a href="https://github.com/aelvan/Preparse-Field-Craft/issues/2" rel="nofollow">remove initial whitespace character</a> from the newly parsed “Searchable Specialisms” field)</p>

<p>Once the field is created, add it to your User field layout (Settings > Users > Fields) - doesn’t matter where.</p>

<p>Finally, update your <code>set results</code> template code to this:</p>

<pre><code>{% set results = craft.users({
    group: 'verified',
    search: 'searchableSpecialisms:"' ~ query ~ '"'
}) %}
</code></pre>

<p>This approach will make it much easier to handle the premium member feature down the road, because you’ll just need to factor in whether they are a premium member or not in the Preparse field settings:</p>

<pre><code>{% set limit = user.isInGroup('premium') ? null : 5 %}
{% for tag in user.specialismTags.limit(limit) %}
    {{ tag.title }}
{% endfor %}
</code></pre>

CC BY-SA 3.0
2015-10-08T17:39:16.423Z
Thanks for this Brandon. **Option 1** isn't really suitable, to me categories should be limited and there could be 100s of possible conditions the users might add. **Option 2** looks like it will do the job! I didn't realise `limit()` could be used on tags (is this a better solution than `user.specialismTags[0:5]`?) **Questions:** *1)* There's [mention of a gotcha](http://bit.ly/1LBTA4R), the user will save out their profile so this won't apply right? *2)* I've not seen `_results.html` written like this before — is there a specific reason to not use dot notation?
Rob
CC BY-SA 3.0
2015-10-08T18:19:53.730Z
You can use the `limit` param any time you’re dealing with an [ElementCriteriaModel](http://buildwithcraft.com/docs/templating/elementcriteriamodel), which is what all the relational fields return. It’s better than the `[0:5]` syntax because that will cause Craft to query the full set of tags and then discard all but the first 5. `limit` will actually limit the SQL query. ; That gotcha shouldn’t matter in this case, right. ; Not sure what you mean by _results.html?
Brandon Kelly
CC BY-SA 3.0
2015-10-08T19:08:45.373Z
Great! I'll use `limit` in future. By `_results.html` I'm referring to your [example demo site](https://github.com/pixelandtonic/HappyLager) and [the docs](http://buildwithcraft.com/docs/templating/search-form) where you use `.getParam('q')` and `.search(query)`. What is the benefit of using your `set results` method and where can it's documentation be found?
Rob
CC BY-SA 3.0
2015-10-09T19:53:19.347Z
Added a couple of changes to your code, seems to be working well! The only issues I can see are that partial words don't return any results (for instance `anx` will not search for `anxiety`, so it has to be exact. I guess you could always pre-search and use a plugin like [Chosen](https://harvesthq.github.io/chosen/) to prepopulate the search form. Also, do you have any suggestions to properly `{% cache %}` the results?
Rob
CC BY-SA 3.0
2015-10-09T23:41:52.120Z
@Rob Partial searching is possible via `anx*`. (See http://buildwithcraft.com/docs/searching for all of the possible search syntaxes.)  Can you post your caching question in a new Q&A thread?
Brandon Kelly
CC BY-SA 3.0
2015-10-12T21:22:47.283Z
Ah I see, I'll have a look around on the docs and see if this can be achieved with some kind of ajax request too. Will do ... Thanks.
Rob
CC BY-SA 3.0
2015-10-06T21:41:35.357Z
2015-10-09T21:29:04.380Z
2015-10-09T21:29:04.380Z
Brandon Kelly
<p>I've read as many forum posts and documentation but am a little stumped over a specific use-case. Currently the search page grabs the url segment, loops through a verified user group, and uses the <code>.shuffle()</code> function to randomise order. </p>

<p>I'm looking to limit search results using <a href="http://buildwithcraft.com/docs/relations" rel="nofollow noreferrer">relations</a> with a <code>customTagsField</code> on a user's profile. It also needs to limit results using only the first 5 tags that the user has entered in <code>customTagField</code>, in the order they are arranged in control panel.</p>

<p><a href="https://i.sstatic.net/OdEw4.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/OdEw4.png" alt="Only the first 5 tags are searched, in the order they&#39;re displayed"></a></p>

<pre><code>&lt;div class="grid-item 1/1"&gt;
    &lt;h1&gt;Search Results&lt;/h1&gt;

    {% set query   = craft.request.getParam('q') %}
    {% set results = craft.users.group('verified').search(query) %}
    {% set users   = shuffle(results) %}

    {% if users|length %}
        &lt;p&gt;{{ users|length }} results:&lt;/p&gt;

        &lt;div class="grid"&gt;
        {% for user in users %}
            &lt;div class="grid-item 1/1 mb"&gt;
                &lt;div {# class="grid-item xs-1/4 sm-1/6 lg-1/8" #}&gt;
                        &lt;img class="img-circle" src="{{ user.photoUrl }}" alt=""&gt;
                      &lt;/div&gt;
                &lt;h2 {# class="grid-item 1/1" #}&gt;{{ user.fullName }}&lt;/h2&gt;
                &lt;div {# class="grid-item 1/1" #}&gt;{{ user.intro }}&lt;/div&gt;
                        &lt;div {# class="grid-item 1/1" #}&gt;
                            &lt;a class="btn" href="/profile/{{ user.username }}"&gt;View counsellor&lt;/a&gt;
                        &lt;/div&gt;
                    &lt;/div&gt;
        {% endfor %}
        &lt;/div&gt;
    {% else %}
        &lt;p&gt;Your search for “{{ query }}” didn’t return any results.&lt;/p&gt;
    {% endif %}
&lt;/div&gt;
</code></pre>

<p>I'm still a bit confused about <code>relatedTo</code> as well as <strong>source</strong> and <strong>target</strong> terminology, even though I've read quite a bit about it!</p>

<p>Is it as simple as changing <code>results</code> to:</p>

<pre><code>{% set results = craft.users.group('verified').relatedTo(customTagsFieldHandle).search(query) %}
</code></pre>

<p>It doesn't seem possible to limit the tags searched using <code>relatedTo</code> (as you can with <a href="https://craftcms.stackexchange.com/questions/8727/is-there-a-way-to-limit-output-of-tags-related-to-an-entry/8729#8729"><code>craft.tags</code></a>, so I expect I'll have to edit the <code>for loop</code> somehow. I know about <a href="http://twig.sensiolabs.org/doc/filters/slice.html" rel="nofollow noreferrer">Twig's slice function</a> but I'm not sure how to go about limiting by a user's tag entries.</p>

<p>Does anyone have suggestions for the optimal way to achieve this?</p>

CC BY-SA 3.0
2015-10-06T13:28:40.380Z
To clarify, you’re saying you have a search form, and you want it to search for _users_ whose selected “Specialism” tags match the search query; but you only want the first 5 tags to be factored in, and any additional tags should be ignored. Correct?
Brandon Kelly
CC BY-SA 3.0
2015-10-06T20:26:07.917Z
@BrandonKelly Got it in one, that's exactly what I'm trying to do. Just to clarify it's the 5 tags in the same order they've been arranged in CP. We may in future allow **premium members** to be searchable for more than 5 tags (likely through another user group) but for now I'm keeping things simple. Tags seemed to be the most sensible choice to have a selectable list of specialties.
Rob
<users><relations><search><tags><set>
Limit search results for users by tag (and limit to 5 tags)
# Limit search results for users by tag (and limit to 5 tags)

(Asked by: username_0 on 2015-10-05)

I've read as many forum posts and documentation but am a little stumped over a specific use-case. Currently the search page grabs the url segment, loops through a verified user group, and uses the .shuffle() function to randomise order. 
I'm looking to limit search results using relations with a customTagsField on a user's profile. It also needs to limit results using only the first 5 tags that the user has entered in customTagField, in the order they are arranged in control panel.


    Search Results

    {% set query   = craft.request.getParam('q') %}
    {% set results = craft.users.group('verified').search(query) %}
    {% set users   = shuffle(results) %}

    {% if users|length %}
        {{ users|length }} results:

        
        {% for user in users %}
            
                
                        
                      
                {{ user.fullName }}
                {{ user.intro }}
                        
                            View counsellor
                        
                    
        {% endfor %}
        
    {% else %}
        Your search for “{{ query }}” didn’t return any results.
    {% endif %}


I'm still a bit confused about relatedTo as well as source and target terminology, even though I've read quite a bit about it!
Is it as simple as changing results to:
{% set results = craft.users.group('verified').relatedTo(customTagsFieldHandle).search(query) %}

It doesn't seem possible to limit the tags searched using relatedTo (as you can with craft.tags, so I expect I'll have to edit the for loop somehow. I know about Twig's slice function but I'm not sure how to go about limiting by a user's tag entries.
Does anyone have suggestions for the optimal way to achieve this?

**Tags:** users, relations, search, tags, set

> **Comments:**
> **username_1**: To clarify, you’re saying you have a search form, and you want it to search for _users_ whose selected “Specialism” tags match the search query; but you only want the first 5 tags to be factored in, and any additional tags should be ignored. Correct?  
> **username_0**: @BrandonKelly Got it in one, that's exactly what I'm trying to do. Just to clarify it's the 5 tags in the same order they've been arranged in CP. We may in future allow **premium members** to be searchable for more than 5 tags (likely through another user group) but for now I'm keeping things simple. Tags seemed to be the most sensible choice to have a selectable list of specialties.  

---

## 1 answers

### Answer by username_1 on 2015-10-06. Score: 3 | Accepted answer

There’s no way to tell the relatedTo param to only factor in the first X relations per source element (the first 5 tags per user, in this case).
I can think of two ways you could accomplish this:
Option 1: Use two Specialism fields
Replace your “Specialism” Tags field with two Categories fields – “Primary Specialism” and “Secondary Specialism”. Limit “Primary” to 5 categories, so no one can ever enter more than 5 specialties in there, and they can list any additional specialties  in the “Secondary” field.
Then from your template, you can limit the search query to only factor in the “Primary” field:
{% set results = craft.users({
    group: 'verified',
    relatedTo: {
        targetElement: craft.categories({
            group: 'specialisms',
            search: query
        }),
        field: 'primarySpecialism'
    }
%}

This method will get more complicated if you do start allowing premium members to be found from both fields down the road; you would need to split it up into two separate user queries – first for the premium members, and then again for the normal members.
Option 2: Automatically store the searchable specialisms in a separate, hidden field
Install the excellent Preparse plugin, and create a new Preparse field called “Searchable Specialisms” with the following Twig code:
{% spaceless %}
    {% for tag in user.specialismTags.limit(5) %}
        {{ tag.title }}
    {% endfor %}
{% endspaceless %}

(Disable the “Show Field” setting so this field doesn’t show up on user profile pages. {% spaceless %} is required to remove initial whitespace character from the newly parsed “Searchable Specialisms” field)
Once the field is created, add it to your User field layout (Settings > Users > Fields) - doesn’t matter where.
Finally, update your set results template code to this:
{% set results = craft.users({
    group: 'verified',
    search: 'searchableSpecialisms:"' ~ query ~ '"'
}) %}

This approach will make it much easier to handle the premium member feature down the road, because you’ll just need to factor in whether they are a premium member or not in the Preparse field settings:
{% set limit = user.isInGroup('premium') ? null : 5 %}
{% for tag in user.specialismTags.limit(limit) %}
    {{ tag.title }}
{% endfor %}

> **Comments:**
> **username_0**: Thanks for this Brandon. **Option 1** isn't really suitable, to me categories should be limited and there could be 100s of possible conditions the users might add. **Option 2** looks like it will do the job! I didn't realise `limit()` could be used on tags (is this a better solution than `user.specialismTags[0:5]`?) **Questions:** *1)* There's [mention of a gotcha](http://bit.ly/1LBTA4R), the user will save out their profile so this won't apply right? *2)* I've not seen `_results.html` written like this before — is there a specific reason to not use dot notation?  
> **username_1**: You can use the `limit` param any time you’re dealing with an [ElementCriteriaModel](http://buildwithcraft.com/docs/templating/elementcriteriamodel), which is what all the relational fields return. It’s better than the `[0:5]` syntax because that will cause Craft to query the full set of tags and then discard all but the first 5. `limit` will actually limit the SQL query. ; That gotcha shouldn’t matter in this case, right. ; Not sure what you mean by _results.html?  
> **username_0**: Great! I'll use `limit` in future. By `_results.html` I'm referring to your [example demo site](https://github.com/pixelandtonic/HappyLager) and [the docs](http://buildwithcraft.com/docs/templating/search-form) where you use `.getParam('q')` and `.search(query)`. What is the benefit of using your `set results` method and where can it's documentation be found?  
> **username_0**: Added a couple of changes to your code, seems to be working well! The only issues I can see are that partial words don't return any results (for instance `anx` will not search for `anxiety`, so it has to be exact. I guess you could always pre-search and use a plugin like [Chosen](https://harvesthq.github.io/chosen/) to prepopulate the search form. Also, do you have any suggestions to properly `{% cache %}` the results?  
> **username_1**: @username_0 Partial searching is possible via `anx*`. (See http://buildwithcraft.com/docs/searching for all of the possible search syntaxes.)  Can you post your caching question in a new Q&A thread?  
> **username_0**: Ah I see, I'll have a look around on the docs and see if this can be achieved with some kind of ajax request too. Will do ... Thanks.  

---

