2

I got users that has 3 Entries fields in their profile: breadForMonday, breadForWednesday and breadForFriday.

I want to differentiate between users with 1, 2 or 3 selected entries. How would I use relatedTo together with and/or and :empty/:notempty?

Something like this:

{% set bread = craft.entries({ section: 'bread' }).limit(null) %}
{# Find users that have selected entries for two out of three fields #}
{% set users = craft.users({
    group: 'customers',
    relatedTo: [
        'and',
        { targetElement: bread, field: 'breadForMonday' },
        { targetElement: bread, field: 'breadForWednesday' }
    ]
}) %}
3

Please don't laugh, but I thought to myself, let's give this a go in Twig and see where it takes me. It very soon began to become clear, that this will end up in lots of criteria models, db queries and a huge pile of Twig code.

So my better answer should be, don't do it in Twig. This is something you should better do in PHP with custom database queries (→ Yii query builder). But now that I've done it, here's a gist of that Twig code.

2
  • Thanks for taking the time to put that together. I was worried that it will involve clunky Twig code, and was thinking about reducing it into a plugin. Got an example on how to do this with the query builder? Sep 4 '15 at 12:00
  • Unfortunatelly there's only very few examples here on Stack Exchange. This might help: craftcms.stackexchange.com/q/7175 or this one: craftcms.stackexchange.com/q/4600.
    – carlcs
    Sep 4 '15 at 12:13

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.