1

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.

2

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()->elements->getCriteria(ElementType::Entry);
    $criteria->section = 'sectionName';
    $criteria->limit = null;

    $query = craft()->elements->buildElementsQuery($criteria);

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

    $query->andWhere($conditions);

    $results = $query->queryAll();

    return EntryModel::populateModels($results);
}
{% set vars = ['foo', 'bar'] %}
{% set entries = craft.myPlugin.getEntriesWithVars(vars) %}
1
  • I might be missing something obvious, but I'm getting a "Column not found" error when trying to do this for "field_researchTheme". I've also tried just straight "researchTheme" as the field name. That field definitely exists on this entry type.
    – JamesNZ
    Sep 27 '16 at 3:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.