How to fetch entries based on contents of several custom fields? I'm currently doing something like this:

{% set vars = "foo, bar" %}

{% set entries1 = craft.entries.section('sectionName').customField1(vars).limit(NULL) %}
{% for entry in entries1 %}
    {% if entry not in allEntries %}
        {% set allEntries = allEntries | merge([entry]) %}
    {% endif %}
{% endfor %}

{% set entries2 = craft.entries.section('sectionName').customField2(vars).limit(NULL) %}
{% for entry in entries2 %}
    {% if entry not in allEntries %}
        {% set allEntries = allEntries | merge([entry]) %}
    {% endif %}
{% endfor %}


But for each custom field I want to check, it's a trip to the database, and I've currently got to check three custom fields. Is there a way to merge these into one trip? I need to know whether the contents of vars are in either custom field. They might be in one, none of both, for example.
No, but this is possible with a few lines of plugin code. You just need to create a DbCommand object from your criteria model and add your WHERE conditions with a OR operator.

Add this function to your Template variable class and you can get the entries from your templates with a single query.

public function getEntriesWithVars($vars)
{
    $criteria = craft()-&gt;elements-&gt;getCriteria(ElementType::Entry);
    $criteria-&gt;section = 'sectionName';
    $criteria-&gt;limit = null;

    $query = craft()-&gt;elements-&gt;buildElementsQuery($criteria);

    $conditions = array(
        'or',
        array('in', 'field_customField1', $vars),
        array('in', 'field_customField2', $vars)
    );

    $query-&gt;andWhere($conditions);

    $results = $query-&gt;queryAll();

    return EntryModel::populateModels($results);
}




{% set vars = ['foo', 'bar'] %}
{% set entries = craft.myPlugin.getEntriesWithVars(vars) %}