Skip to content

Commit

Permalink
Fix: many to many relations from DB did not work (#1174)
Browse files Browse the repository at this point in the history
Co-authored-by: gluafamichl <>
  • Loading branch information
gluafamichl authored Jan 23, 2025
1 parent df3c233 commit 6297209
Showing 1 changed file with 17 additions and 18 deletions.
35 changes: 17 additions & 18 deletions src/inc/apiv2/common/AbstractModelAPI.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -255,33 +255,32 @@ final protected static function getManyToOneRelationViaIntermediate(
): array {
assert($intermediateFactory instanceof AbstractModelFactory);
assert($targetFactory instanceof AbstractModelFactory);
$retval = array();


$many2Many = array();

/* Retrieve Parent -> Intermediate -> Target objects */
$objectIds = [];
foreach ($objects as $object) {
foreach($objects as $object) {
$kv = $object->getKeyValueDict();
$objectIds[] = $kv[$objectField];
}
$qF = new ContainFilter($filterField, $objectIds, $intermediateFactory);
$jF = new JoinFilter($intermediateFactory, $joinField, $joinField);
$hO = $targetFactory->filter([Factory::FILTER => $qF, Factory::JOIN => $jF]);

/* Build mapping Parent -> Intermediate */
$i2p = [];
foreach ($hO[$intermediateFactory->getModelName()] as $intermidiateObject) {
$kv = $intermidiateObject->getKeyValueDict();
$i2p[$kv[$joinField]] = $kv[$filterField];

$intermediateObjectList = $hO[$intermediateFactory->getModelName()];
$targetObjectList = $hO[$targetFactory->getModelName()];

$intermediateObject = current($intermediateObjectList);
$targetObject = current($targetObjectList);

while ($intermediateObject && $targetObject) {
$kv = $intermediateObject->getKeyValueDict();
$many2Many[$kv[$filterField]][] = $targetObject;

$intermediateObject = next($intermediateObjectList);
$targetObject = next($targetObjectList);
}

/* Associate Target -> Parent (via Intermediate) */
foreach ($hO[$targetFactory->getModelName()] as $targetObject) {
$parent = $i2p[$targetObject->getKeyValueDict()[$joinField]];
$retval[$parent][] = $targetObject;
}

return $retval;
return $many2Many;
}

/**
Expand Down

0 comments on commit 6297209

Please sign in to comment.