protected function updateRelation($contenttype, $contentId, $relation)
{
$tablename = $this->getTablename("relations");
// Get the current values from the DB.
$query = sprintf("SELECT id, to_contenttype, to_id FROM %s WHERE from_id=? AND from_contenttype=?", $tablename);
$currentvalues = $this->app['db']->executeQuery($query, [$contentId, $contenttype['slug']], [\PDO::PARAM_INT, \PDO::PARAM_STR])->fetchAll();
// And the other way around.
$query = sprintf("SELECT id, from_contenttype AS to_contenttype, from_id AS to_id FROM %s WHERE to_id=? AND to_contenttype=?", $tablename);
$currentvalues2 = $this->app['db']->executeQuery($query, [$contentId, $contenttype['slug']], [\PDO::PARAM_INT, \PDO::PARAM_STR])->fetchAll();
// Merge them.
$currentvalues = array_merge($currentvalues, $currentvalues2);
// Delete the ones that have been removed, but only if the contenttype defines the relations. For if we have
// example, if we have a relation from 'pages' to 'entries', do not delete them when editing an 'entry'.
foreach ($currentvalues as $currentvalue) {
if ((!isset($relation[$currentvalue['to_contenttype']]) || !in_array($currentvalue['to_id'], $relation[$currentvalue['to_contenttype']])) && isset($contenttype['relations'][$currentvalue['to_contenttype']])) {
$this->app['db']->delete($tablename, ['id' => $currentvalue['id']]);
}
}
// Make an easier array out of $currentvalues.
$tempvalues = $currentvalues;
$currentvalues = [];
foreach ($tempvalues as $tempvalue) {
$currentvalues[] = $tempvalue['to_contenttype'] . "/" . $tempvalue['to_id'];
}
// Add the ones not yet present.
if (!empty($relation)) {
foreach ($relation as $toContenttype => $newvalues) {
foreach ($newvalues as $value) {
if (!in_array($toContenttype . "/" . $value, $currentvalues) && !empty($value)) {
// Insert it!
$row = ['from_contenttype' => $contenttype['slug'], 'from_id' => $contentId, 'to_contenttype' => $toContenttype, 'to_id' => $value];
$this->app['db']->insert($tablename, $row);
}
}
}
}
}