/**
* @param string $fieldName
* @return $this
* @throws MappingException
*/
private function fromReference($fieldName)
{
if (!$this->class->hasReference($fieldName)) {
MappingException::referenceMappingNotFound($this->class->name, $fieldName);
}
$referenceMapping = $this->class->getFieldMapping($fieldName);
$targetMapping = $this->dm->getClassMetadata($referenceMapping['targetDocument']);
parent::from($targetMapping->getCollection());
if ($referenceMapping['isOwningSide']) {
if ($referenceMapping['storeAs'] !== ClassMetadataInfo::REFERENCE_STORE_AS_ID) {
throw MappingException::cannotLookupNonIdReference($this->class->name, $fieldName);
}
$this->foreignField('_id')->localField($referenceMapping['name']);
} else {
if (isset($referenceMapping['repositoryMethod'])) {
throw MappingException::repositoryMethodLookupNotAllowed($this->class->name, $fieldName);
}
$mappedByMapping = $targetMapping->getFieldMapping($referenceMapping['mappedBy']);
if ($mappedByMapping['storeAs'] !== ClassMetadataInfo::REFERENCE_STORE_AS_ID) {
throw MappingException::cannotLookupNonIdReference($this->class->name, $fieldName);
}
$this->localField('_id')->foreignField($mappedByMapping['name']);
}
return $this;
}