Calling Related Entries using the Element API I have two sections, each with a single entry type:


Sites
Locations


In the Locations entry type I have a Entries field called Site that you can use to relate a Location to a Site entry.

My questions is: how do I show which locations were related to a Site entry when using the Element API? I'd like to display it as an array when using a sites/.json endpoint.

This is what I've tried, but it breaks the endpoint:

'v1/sites/&lt;entryId:\d+&gt;.json' =&gt; function($entryId) {
  return [
    'elementType' =&gt; 'Entry',
    'criteria' =&gt; ['id' =&gt; $entryId],
    'first' =&gt; true,
    'transformer' =&gt; function(EntryModel $entry) {
      $locations = $entry-&gt;getChildren()-&gt;type('locations')-&gt;find();
      foreach ($locations as $location) {
        $locationsInfo[] = [
          'name' =&gt; $location-&gt;title
        ];
      }

      return [
        'id' =&gt; $entry-&gt;id,
        'name' =&gt; $entry-&gt;title,
        'tagline' =&gt; $entry-&gt;tagline,
        'about' =&gt; $entry-&gt;about-&gt;getParsedContent(),
        'locations' =&gt; $locationsInfo,
        'jsonUrl' =&gt; UrlHelper::getUrl("v1/sites/{$entry-&gt;id}.json")
      ];
    },
  ];
},
You’d do this with a brand new element query using the relatedTo param.



Craft 2:

// This is the PHP equivalent of typing `craft.entries()` in a template:
$criteria = craft()-&gt;elements-&gt;getCriteria(ElementType::Entry);

// Only fetch Location entries that are related to the Site entry:
$criteria-&gt;section = 'locations';
$criteria-&gt;relatedTo = ['targetElement' =&gt; $entry];

$locations = $criteria-&gt;find();


Craft 3:

// This is the PHP equivalent of typing `craft.entries()` in a template:
$query = \craft\elements\Entry::find();

// Only fetch Location entries that are related to the Site entry:
$query-&gt;section('locations');
$query-&gt;relatedTo(['targetElement' =&gt; $entry]);

$locations = $query-&gt;all();