craftcms / element-api

Create a JSON API/Feed for your elements in Craft.
MIT License
498 stars 56 forks source link

Can't get all matrix field entries #105

Closed boxadesign closed 5 years ago

boxadesign commented 5 years ago

I'm getting matrix block content from an entry type which works fine for the most part. It's probably clearer to just paste in the code:

Current element api code:


$relationsData = [];    
if($entry->relatedContent){
    $index = -1;
    foreach ($entry->relatedContent->all() as $block) {
        switch ($block->type->handle) {
            case 'relateContent':
                $index++;
                $relatedFeaturedEntries =  $block->featured->first();
                $relatedSubEntries =  $block->related->first();
                $relationsData[$index] = [
                    'title' => $relatedFeaturedEntries->title,
                    'url' => $relatedFeaturedEntries->url
                ];
                $relationsData[$index]['subItems'] = [];
                $relationsData[$index]['subItems'][] = [
                    'title' => $relatedSubEntries->title,
                    'url' => $relatedSubEntries->url
                ];
            break;
        }
    }
}

Which outputs:

      "relations": [
        {
          "title": "Testing workflow",
          "url": "http://localhost/blah",
          "subItems": [
            {
              "title": "Help & Guidance",
              "url": "http://localhost/help-guidance"
            }
          ]
        },
        {
          "title": "Taking part in the blah",
          "url": "http://localhost/blah",
          "subItems": [
            {
              "title": "blah timeline",
              "url": "http://localhost/blah"
            }
          ]
        },
        {
          "title": "Testing workflow",
          "url": "http://localhost/blah",
          "subItems": [
            {
              "title": "Completing on paper",
              "url": "http://localhost/blah"
            }
          ]
        }
      ],

There should be more subItems in each subItems array but I am only getting the first because I'm fetching them using $relatedSubEntries = $block->related->first(); But nothing else works and just errors i.e. all() or removing first()