public function addRelation($relationName, Document $document)
{
if (!$this->isRelationExists($relationName)) {
throw new \Exception('Relation "' . $relationName . '" not configured');
}
$relation = $this->relations[$relationName];
list($relationType, $relatedCollectionName, $field) = $relation;
$relatedCollection = $this->document->getCollection()->getDatabase()->getCollection($relatedCollectionName);
if (!$relatedCollection->hasDocument($document)) {
throw new \Sokil\Mongo\Exception('Document must belongs to related collection');
}
switch ($relationType) {
case Document::RELATION_BELONGS:
if (!$document->isStored()) {
throw new \Sokil\Mongo\Exception('Document ' . get_class($document) . ' must be saved before adding relation');
}
$this->document->set($field, $document->getId());
break;
case Document::RELATION_HAS_ONE:
if (!$this->document->isStored()) {
throw new \Sokil\Mongo\Exception('Document ' . get_class($this) . ' must be saved before adding relation');
}
$document->set($field, $this->document->getId())->save();
break;
case Document::RELATION_HAS_MANY:
if (!$this->document->isStored()) {
throw new \Sokil\Mongo\Exception('Document ' . get_class($this) . ' must be saved before adding relation');
}
$document->set($field, $this->document->getId())->save();
break;
case Document::RELATION_MANY_MANY:
$isRelationListStoredInternally = isset($relation[3]) && $relation[3];
if ($isRelationListStoredInternally) {
$this->document->push($field, $document->getId())->save();
} else {
$document->push($field, $this->document->getId())->save();
}
break;
default:
throw new \Sokil\Mongo\Exception('Unsupported relation type "' . $relationType . '" when resolve relation "' . $relationName . '"');
}
return $this;
}