1

I think the best way to pose this question is by giving an example:

Given a variable $query of type craft\elements\db\EntryQuery, I'd like to get entries from 2 different sections: "people" and "news". Of the entries from the "people" section, I only want ones with entry type "Employees". How would I set this up so that the "type" filter only applies to 1 section? If I were querying them individually, they would look like this:

$query->section('people')->type('Employees');
$query->section('insights');

How can I do this in 1 query? Thanks!

  • Alternatively, could I create 2 queries and combine them somehow? I need to preserve it as a query, so I can't just use .all() and merge the arrays. – Adam Tsai Sep 15 at 18:38
2

I'm not sure you can achieve this in one query.

The easiest solution I can think of to your problem requires 3 queries:

{% set peopleIds = craft.entries().section('people').type('Employees').ids() %}
{% set insightIds = craft.entries().section('insights').ids() %}
{% set query = craft.entries().id(peopleIds|merge(insightIds))

The first 2 queries are executed and return the ids of the matching entries. You can then create your EntryQuery using the ids as the only criterion.

| improve this answer | |
2

Thank you @nstCactus, that's a great idea! Just for anyone looking for the PHP equivalent:

$peopleIds = \craft\elements\Entry::find()->section('people')->type('Employees')->ids();
$insightIds = \craft\elements\Entry::find()->section('insights')->ids();
$query->id(array_merge($peopleIds, $insightsIds));
| improve this answer | |

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.