We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
  • I'm working on an "element inventory" application, that lists information about each element in my MODX installation. One of the things I want to do is, for each TV, show a count of all the published resources that have a TV value for that TV.

    I'm using code that looks like this:

    $collection = $modx->getCollectionGraph('modTemplateVarResource', '{"Resource":{}}',  array('tmplvarid'=>$id, 'Resource.published'=>1));


    This works, but it is taking forever. My snippet runs in about 2 seconds without it, about 9-10 seconds when this line of code is run.

    Is there a faster way to get the answer I'm looking for? I chose getCollectionGraph because it lets me get the actual resource objects, which is the only way I know of to see if they are published or not. I could have used $tv->getMany to get the templateVarResource objects, but then I'd still need to get the related Resource object for each one to see if it is published.

    Any thoughts?
    • I'm looking at getCount as a solution, because I don't need the actual objects, just how many of them there are. Stay tuned...
      • Here's what I came up with:

        $tvrs = $tv->getMany('TemplateVarResources');
        $ids = array_map( function ($tvr) { return $tvr->get('contentid'); }, $tvrs);
        $idlist = implode(',',$ids);
        $query = $modx->newQuery('modResource');
        $query->where(array(
        		     'modResource.id:IN' => $ids, 
        		     'modResource.published'=>1));
        $published_count = $modx->getCount('modResource',$query);


        This returns all of the "published resources" counts for each TV in my MODX installation in about 3.5 seconds (as compared to 9-10 seconds for the original method).