Get all childs of parent with specific template and set tv value

Hi everyone! How to get all childs of parent with specific template and set tv value through the console? Here is my beginning code:

<?php
if(!$docs = $modx->getCollection('modResource', array(
    'template' => 11
))){return;}
foreach($docs as $doc){
    $doc->setTVValue(2,'dir');
    $doc->save();
}

Thanks in advance!

if you only want the direct children you can set the parent in your query.

$parent_id = 10;
if(!$docs = $modx->getCollection('modResource', array(
    'template' => 11, 'parent' => $parent_id
))){return;}

If you want all the children in the hierarchy you could use the function getChildIds():

$parent_id = 10;
$children = $modx->getChildIds($parent_id);
if(!$docs = $modx->getCollection('modResource', array(
    'template' => 11, 'id:IN' => $children
))){return;}
1 Like

The first solution is fine, but I have many parents. I need to change the tv each child of each parent with template 11. I suppose I need to use two foreach loops.

You can do this with 2 foreach loops or with a query that uses a join:

$q = $modx->newQuery('modResource');
$q->innerJoin('modResource','Parent');
$q->where(array(
    'template' => 11, //template of child resource
    'Parent.template' => 11 //template of parent resource
));
if(!$docs = $modx->getCollection('modResource', $q)){return;}
1 Like

This topic was automatically closed 2 days after discussion ended and a solution was marked. New replies are no longer allowed. You can open a new topic by clicking the link icon below the original post or solution and selecting “+ New Topic”.