So here's an example from getCollectionGraph rtfm page covering a very common use case: get resources with their related TVs.
$pages = $modx->getCollectionGraph('modResource', '{"TemplateVarResources":{}}', array('parent'=>12));
foreach ($pages as $p) {
foreach ($p->TemplateVarResources as $tv) {
// Do stuff here with the TV
$tv_array = $tv->toArray();
$tv->get('value');
}
}
When i read the documentation first i thought: "Great, each resource in the collection will get an attached collection of TVs for easy access."
So I expected to be able to do something as stimple as this (using the example above):
$pages = $modx->getCollectionGraph('modResource', '{"TemplateVarResources":{}}', array('parent'=>12));
$results = array();
foreach ($pages as $p) {
$results['pagetitle'] = $p->get('pagetitle');
$results['date'] = $p->get('createdon');
$results['tv1'] = $p->TemplateVarResources->get('tv1');
$results['tv2'] = $p->TemplateVarResources->get('tv2');
}
But when i ran that i got "calling get() function on a non-object" error. Going back to documentation and some other examples it turns out that you have to iterate through TemplateVarResources with an inner loop to get tv values before they can be used. So i had to create another array in the form 'tv.name'=>'tv.value' just to be able to use tvs with the $p object.
Granted that i'm new to XPDO and am learning as i go along but the above approach seems rather inelegant.
Isn't the whole point of getCollectionGraph to elegantly return entities with their relationships? And it would make sense to allow direct named access to those relationships once you have the handle on the main object, wouldn't it.
Of course it's entirely possible that i'm missing something obvious. And perhaps to satisfy many entity types that getCollectionGraph needs to support it must operate in such a way. But since tvs are such a big part of MODx i would think that they should be treated nicer. Perhaps a getCollectionWithTVsGraph method to make getting resources with their tvs using api easier.
And while I'm making a wishlist it would be nice to have a simpler way to select which TVs to include in the returned collection. Currently is not possible to do that with the standard getCollectionGraph call. The only way to do that is to define a newQuery separately and pass it into getCollectionGraph method like so (my actual code not related to the example above):
$criteria = array();
$criteria['modResource.id:IN'] = $selectedIDs;
$criteria['TemplateVarResources.tmplvarid:IN'] = array(44,41,67,65,61,66); //specify which TVs to grab
$criteria = $modx->newQuery('modResource', $criteria);
$results = $modx->getCollectionGraph('modResource', '{"TemplateVarResources":{"TemplateVar":{}}}', $criteria);
Just some muzings late at night after fighting with getCollectionGraph for a few hours.