A couple of issues:
First, the EntryModel::getParent()
method returns an EntryModel, not an ElementCriteriaModel, which means that calling getParent()->first()
will throw an exception. In other words, you'll need to remove the call to first()
.
Second, you'll need to be specific about which fields you want to return from your parent entry – just passing in the raw EntryModel won't work – so your code should look something like this:
'transformer' => function(EntryModel $entry) {
$parent = $entry->getParent();
return [
'title' => $entry->title,
'url' => $entry->url,
'level' => $entry->level,
'parent' => $parent ? [
'title' => $parent->title,
'url' => $parent->url,
'someCustomField' => $parent->someCustomField,
] : null,
];
},
In the above, I'm using a ternary operator to conditionally include the array containing the parent entry's data (the condition being if the parent entry exists or not). If you want your code to be less "inline", you could also do something like this:
'transformer' => function (EntryModel $entry) {
$parent = $entry->getParent();
$return = [
'title' => $entry->title,
'url' => $entry->url,
'level' => $entry->level
];
if ($parent) {
$return['parent'] = [
'title' => $parent->title,
'url' => $parent->url,
'someCustomField' => $parent->someCustomField,
];
}
return $return;
},
Finally, if you need to be specific about the parent entry's level, you'll need to swap out the getParent()
method for EntryMode::getAncestors()
(which does return an ElementCriteriaModel). Here's how you'd get the top level parent:
$parent = $entry->getAncestors()->first();
...and since getAncestors()
returns an ECM, pulling a parent entry with a specific level is trivial:
$parent = $entry->getAncestors()->level(2)->first();