public function removeRelation($relationName, Document $document = null) { 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 ($document && !$relatedCollection->hasDocument($document)) { throw new \Sokil\Mongo\Exception('Document must belongs to related collection'); } switch ($relationType) { case Document::RELATION_BELONGS: $this->document->unsetField($field)->save(); break; case Document::RELATION_HAS_ONE: $document = $this->getRelated($relationName); if (!$document) { // relation not exists return $this; } $document->unsetField($field)->save(); break; case Document::RELATION_HAS_MANY: if (!$document) { throw new \Sokil\Mongo\Exception('Related document must be defined'); } $document->unsetField($field)->save(); break; case Document::RELATION_MANY_MANY: if (!$document) { throw new \Sokil\Mongo\Exception('Related document must be defined'); } $isRelationListStoredInternally = isset($relation[3]) && $relation[3]; if ($isRelationListStoredInternally) { $this->document->pull($field, $document->getId())->save(); } else { $document->pull($field, $this->document->getId())->save(); } break; default: throw new \Sokil\Mongo\Exception('Unsupported relation type "' . $relationType . '" when resolve relation "' . $relationName . '"'); } return $this; }