public function saveRelations()
{
// Get all the new keys
$newKeys = array();
if ($this->data instanceof DataModel\Collection) {
foreach ($this->data as $item) {
if ($item instanceof DataModel) {
$newKeys[] = $item->getId();
} elseif (!is_object($item)) {
$newKeys[] = $item;
}
}
}
$newKeys = array_unique($newKeys);
$db = $this->parentModel->getDbo();
$localKeyValue = $this->parentModel->getFieldValue($this->localKey);
// Kill all existing relations in the pivot table
$query = $db->getQuery(true)->delete($db->qn($this->pivotTable))->where($db->qn($this->pivotLocalKey) . ' = ' . $db->q($localKeyValue));
$db->setQuery($query);
$db->execute();
// Write the new relations to the database
$protoQuery = $db->getQuery(true)->insert($db->qn($this->pivotTable))->columns(array($db->qn($this->pivotLocalKey), $db->qn($this->pivotForeignKey)));
$i = 0;
$query = null;
foreach ($newKeys as $key) {
$i++;
if (is_null($query)) {
$query = clone $protoQuery;
}
$query->values($db->q($localKeyValue) . ', ' . $db->q($key));
if ($i % 50 == 0) {
$db->setQuery($query);
$db->execute();
$query = null;
}
}
if (!is_null($query)) {
$db->setQuery($query);
$db->execute();
}
}