public function establishLinks(Schema $schema, LinkEntity $linkEntity, $oneFkColumnName, $oneId, $otherFkColumnName, array $otherIds, Audit $audit) { // Get the id's of all existing links. $scope = Scope::parseValue(Scope::VALUE_P_ALL); $query = new QueryEntity($linkEntity, $this->defaultQueryContext, $scope); $query->addWhereClause($oneFkColumnName, $oneId); $mySQLi = $schema->getMySQLi(); $queryString = $query->getQueryString(); $queryResult = $mySQLi->query($queryString); if (!$queryResult) { throw new Exception("Error fetching '{$otherFkColumnName}' properties of link entity " . $linkEntity->getName() . "[{$oneId}] - {$mySQLi->error}\n<!--\n{$queryString}\n-->"); } // Compose a list of otherIds that must be deleted and adjust $otherIds, so it will only contain links that // must be created. $surplusOtherIds = array(); while ($dbObject = $queryResult->fetch_assoc()) { $existingOtherId = $dbObject[$otherFkColumnName]; $key = array_search($existingOtherId, $otherIds); if ($key !== FALSE) { // The link is already there. unset($otherIds[$key]); } else { $surplusOtherIds[] = $existingOtherId; } } $queryResult->close(); // Delete surplus links. if (count($surplusOtherIds) > 0) { $propertyValues = array(); $propertyValues[$oneFkColumnName] = $oneId; $propertyValues[$otherFkColumnName] = $surplusOtherIds; $this->terminateLinks($schema, $linkEntity, $propertyValues, $audit); } // Create missing links. if (count($otherIds) > 0) { $propertyValues = array(); $propertyValues[$oneFkColumnName] = $oneId; foreach ($otherIds as $otherId) { // Pass a NULL to indicate that a new link object must be inserted. $propertyValues[$otherFkColumnName] = $otherId; $this->insertOrUpdate($schema, $linkEntity, NULL, $propertyValues, $audit); } } }