Search for entries with matrix field's value I'm building a travel site containing Campaigns (entries)

Each of these campaigns has multiple travel dates, modelled by a matrix field of

[startDate, endDate, price]

I want to do the following searches:


Campaigns with a travel startDate next month
Campaigns whose duration is more than 30 days and less than 60 days (endDate-startDate)
One of those criteria
All of the above criteria


How can this be achieved with twig template or custom controller?

PS: I looked into relations but that only applies to entries field, not matrix, and neither does it allow filtering on the related entity.
What I've done in a comparable situation is to add a hidden field to that entry type. And then I save Matrix data to that field on every save by listening to onBeforeSaveEntry events.

This makes the access to such processed Matrix data in templates or other parts of your plugin (i.e. getEntryTableAttributeHtml) very easy.

Event handler

craft()-&gt;on('entries.onBeforeSaveEntry', function(Event $event)
{
    $entry = $event-&gt;params['entry'];

    if($entry-&gt;section['handle'] == 'campaigns')
    {
        $longTravels = false;

        foreach ($entry-&gt;travelDates as $travelDate)
        {
            $duration = $travelDate-&gt;startDate-&gt;diff($travelDate-&gt;endDate);

            if ($duration &gt; new DateInterval('P30D') &amp;&amp; $duration &lt; new DateInterval('P60D'))
            {
                $longTravels = true;
                break;
            }
        }

        // Set value for hidden field 'longTravels'
        $entry-&gt;getContent()-&gt;longTravels = $longTravels;
    }
});


CSS for hidden field type

{% set hiddenField %}
    #fields-{{ id }}-field {
        display: none;
    }
{% endset %}

{% includeCss hiddenField %}