2

I have a channel (projects) that has two different entries fields (year & research theme), both of which I want to be able to search in a plugin.

The docs for the relatedTo entries method show under the heading "Passing Multiple Relation Criteria" that it's possible to do this within twig, however I'm not sure how to do this in my plugin using php. Obviously the below won't work:

# Find all projects that match the supplied year and research theme.
$projectCriterea = craft()->elements->getCriteria(ElementType::Entry);
$projectCriterea->section = 'projects';

# Something like this?
$projectCriterea->customField1->relatedTo = $yearEntryModel;
$projectCriterea->customField2->relatedTo = $researchThemeEntryModel;

$projects = $projectCriterea->find();

Any help would be amazing. Thanks.

2

I need someone more experienced with Craft to vet this, but it seems that this is working:

Supplying an array to relatedTo returns results if it matches one OR the other entry.

$projectCriterea = craft()->elements->getCriteria(ElementType::Entry);
$projectCriterea->section = 'projects';
$projectCriterea->relatedTo = [$themeEntry, $yearCat];
$projectResults = $projectCriterea->find();

If you supply "and" as the first entry in the array, it only returns results that are related to BOTH entries.

$projectCriterea = craft()->elements->getCriteria(ElementType::Entry);
$projectCriterea->section = 'projects';
$projectCriterea->relatedTo = ["and", $themeEntry, $yearCat];
$projectResults = $projectCriterea->find();

This was figured out by tinkering and guessing, hence I'm not sure it's the "correct" way to do this. It also doesn't let me search individual custom entries type fields, but this does do what I was after.

  • Hey @JamesNZ – your code looks legit. For some more relatedTo examples – including how to search for relations made in specific fields – check out my answer to a similar question. – Mats Mikkel Rummelhoff Sep 27 '16 at 22:05
  • Hey @mats-mikkel-rummelhoff - Perfect! That shows me exactly what I wanted to do next. Thanks :) – JamesNZ Sep 27 '16 at 23:04

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.