getMany results adding up

Continuing the discussion from Save on-the-fly created form-inputs to custom database:

The Extras are shown, but are not limited to the belonging car.

This here works somewhat, but adds up the extras pretty quirky – minified version of my snippet:

$cars = $modx->getCollection('Cars');

foreach($cars as $car) {

	$carExtras = $car->getMany('Extras', [
		'car_id' => $car->get('id')
	foreach ($carExtras as $carExtra) {
		$extraItem .= $carExtra->get('extra_name');

	$output .= other stuff;
	$output .= $doc->get('category').$extraItem;

return $output;

When you call getMany on a car you don’t have to specify the id. The code should be able to derive that from the relationship in the schema (if the schema is correct.)

$carExtras = $car->getMany('Extras');

Also, the 'Extras' in this call has to be the alias of the relationship in the schema.

See the added line in the code above.

1 Like

That’s it, thank you Bob!
Thanks for your input, too @halftrainedharry

So, what is the not-nooby-way of writing this? How would you write something like this? Would using getCollectionGraph look smth like this?

$cars = $modx->getCollectionGraph('Cars');
foreach ($cars as $car) {
	$extraItem = "";
	foreach ($car->getMany('Extras') as $carExtra) {
        $extraItem .= $carExtra->get('extra_name');

    $output .= other stuff;
    $output .= $car->get('category').$extraItem;

return $output;

You have to define the graph parameter:

$cars = $modx->getCollectionGraph('Cars', '{"Extras":{}}');

I see, thanks for the hint.

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”.