private function fixMnReferences()
{
$referencesToSave = $this->getExistingMnReferences();
$vpIdsToLoad = $this->getAllVpIdsUsedInReferences($referencesToSave);
$idMap = $this->getIdsForVpIds($vpIdsToLoad);
$hasAllIds = $this->idMapContainsAllVpIds($idMap, $vpIdsToLoad);
if (!$hasAllIds) {
return false;
}
foreach ($referencesToSave as $reference => $relations) {
if ($this->entityInfo->isVirtualReference($reference)) {
continue;
}
$referenceDetails = ReferenceUtils::getMnReferenceDetails($this->dbSchema, $this->entityName, $reference);
$prefixedTable = $this->database->prefix . $referenceDetails['junction-table'];
$sourceColumn = $referenceDetails['source-column'];
$targetColumn = $referenceDetails['target-column'];
$valuesForInsert = array_map(function ($relation) use($idMap) {
$sourceId = $idMap[$relation['vp_id']];
$targetId = $idMap[$relation['referenced_vp_id']];
return "({$sourceId}, {$targetId})";
}, $relations);
$sql = sprintf("SELECT id FROM %s WHERE HEX(vp_id) IN ('%s')", $this->database->vp_id, join("', '", array_map(function ($entity) {
return $entity['vp_id'];
}, $this->entities)));
$processedIds = array_merge($this->database->get_col($sql), $this->deletedIds);
if ($this->isSelectiveSynchronization) {
if (count($processedIds) > 0) {
$this->database->query("DELETE FROM {$prefixedTable} WHERE {$sourceColumn} IN (" . join(", ", $processedIds) . ")");
}
} else {
$this->database->query("TRUNCATE TABLE {$prefixedTable}");
}
$valuesString = join(", ", $valuesForInsert);
$insertSql = "INSERT IGNORE INTO {$prefixedTable} ({$sourceColumn}, {$targetColumn}) VALUES {$valuesString}";
$this->database->query($insertSql);
}
return true;
}