@param Entity $middleEntity
@param        $foreignKey
@param        $primaryValue

@return \Pckg\CollectionInterface
436892
public function getMiddleCollection(Entity $middleEntity, $foreignKey, $primaryValue)
    {
        return (new GetRecords($middleEntity->where($foreignKey, $primaryValue)))->executeAll();
    }
21838
public function getCollection($property, $model = null, $primary = null) {
		$list = $this->getList($property);
		
		// Integrity checking
		foreach ($list as $key => $item) {
			if ($item === null) {
				unset($list[$key]);
				continue;
			}
			
			if (! is_object($item)) {
				throw new Exception('Unable to create a collection of non objects');
			}
			
			if (! $item instanceof ModelInterface) {
				throw new Exception('Object must implements "ModelInterface" to be in collection');
			}
		}
		
		// Model's class name resolve
		if ($model === null && isset($item) && $item->hasCollection()) {
			$model = $item->getCollection()->getModel();
		}
		
		if ($model === null && isset($item)) {
			$currentClass   = get_class($item);
			$extensionStack = array($currentClass);
			
			while ($currentClass = get_parent_class($currentClass)) {
				$extensionStack[] = $currentClass;
			}
			
			$primaryIndex = array_search(self::PRIMARY_MODEL, $extensionStack);
			
			if ($primaryIndex === 0 || $primaryIndex === false) {
				$model = self::PRIMARY_MODEL;
			} else {
				$model = $extensionStack[$primaryIndex - 1];
			}
		}
		
		// Primary resolve
		if ($primary === false) {
			$primary = null;
		} else if ($primary === null && isset($item) && $item->hasCollection()) {
			$primary = $item->getCollection()->getPrimary();
		}
		
		$collection = new self($list, $model, $primary);
		
		if ($this->hasLocator()) {
			$collection->setLocator($this->getLocator());
		}
		
		return $collection;
	}
1259870
public function set($virtualProperty, $relationEntity)
    {
        // Check for existing of the relation property
        if (! in_array($virtualProperty, $this->structure->relationProperties) || ! isset($this->structure->relations[$virtualProperty])) {
            throw new RelationException("Relation not defined!"); // @codeCoverageIgnore
        }

        // Make cache array if needed, for lazy loading
        if (! isset(self::$lazy[get_class($this->entity)][$virtualProperty])) {
            self::$lazy[get_class($this->entity)][$virtualProperty] = array();
        }

        /** @var Relation $relation */
        $relation = $this->structure->relations[$virtualProperty];
        if (! $relation instanceof Relation) {
            throw new RelationException("Relation indexing failed, something is really wrong, please report! Fetch proprty no instance of relation!"); // @codeCoverageIgnore
        }

        // Can only set OneToOne and ManyToOne
        if (! $relation instanceof OneToOne && ! $relation instanceof ManyToOne) {
            throw new RelationException("Only relations OneToOne and ManyToOne could be set!"); // @codeCoverageIgnore
        }

        // If NULL then set null into the entity id column (fk)
        if ($relationEntity === null) {
            // Set null
            $this->entity->{$relation->join->column} = null;
            return;
        }

        // Get target structure
        $targetStructure = EntityManager::getInstance()->getEntityStructure($relationEntity);

        // Check if relationEntity is saved, if not throw exception!
        if (! $relationEntity->_saved) {
            throw new RelationException("Save the relationship entity first!");
        }

        // Set the id in the from entity
        $id = $relationEntity->{$targetStructure->primaryColumn->propertyName};
        $this->entity->{$relation->join->column} = $id;

        // Set the cache
        self::$lazy[get_class($this->entity)] [$virtualProperty] [$id] = $relationEntity;
    }
725422
public function manyToMany ($relatedTable, $relationalTable, $relatedKey = null, $key = null, $relationIdentifier = null)
		{
			if (is_null($relationIdentifier)) {
				$relationIdentifier = $relatedTable;
			}

			$this->relations[$relationIdentifier] = new ManyToMany(
				$this,
				$this->schema->getTable($relatedTable, true),
				$this->schema->getTable($relationalTable, true),
				$key,
				$relatedKey
			);

			return $this;
		}
1350574
@Override
	public T delete(X primaryID) {
		if(primaryID == null) {
			return null;
		}
		
		T entity = get(primaryID);
		if(entity == null) {
			return null;
		}
		
		this.mongoTemplate.remove(entity);
		return entity;
	}
1117458
void buildIntermediateManyToManyManyToMany(Relation middleToLeft, Entity middleEntity, Relation middleToRight) {
        // MANY TO MANY
        // Note: if the manyToManyConfig is null, by convention, we create the m2m relation

        Namer toNamer = relationUtil.getManyToManyNamer(middleToLeft.getTo(), middleToRight.getFromAttribute().getColumnConfig(), middleToRight.getTo());
        Namer fromNamer = relationUtil.getManyToManyNamer(middleToRight.getTo(), middleToLeft.getFromAttribute().getColumnConfig(), middleToLeft.getTo());

        ManyToMany m2m = new ManyToMany(fromNamer, toNamer, middleEntity, middleToLeft, middleToRight);
        ManyToManyConfig m2mConfig = middleToRight.getFromAttribute().getColumnConfig().getManyToManyConfig();
        m2m.setCascadeGetter(m2mConfig);
        m2m.setFetchTypeGetter(m2mConfig);
        m2m.setOrderByGetter(m2mConfig);

        setLabelPlural(m2mConfig, m2m);
        initDisplayOrderAsString(m2mConfig, m2m);
        configureActions(m2m, cfg().getDefaultManyToManyConfig(), m2mConfig);
        middleToLeft.getToEntity().addRelation(m2m);

        if (shouldCreateInverse(m2m)) {
            // MANY TO MANY inverse
            ManyToMany inverseM2m = (ManyToMany) m2m.createInverse(); // TODO: fix cast ?
            ManyToManyConfig inverseM2mConfig = middleToLeft.getFromAttribute().getColumnConfig().getManyToManyConfig();
            inverseM2m.setCascadeGetter(inverseM2mConfig);
            inverseM2m.setFetchTypeGetter(inverseM2mConfig);
            inverseM2m.setOrderByGetter(inverseM2mConfig);
            setLabelPlural(inverseM2mConfig, inverseM2m);
            initDisplayOrderAsString(inverseM2mConfig, inverseM2m);
            configureActions(inverseM2m, cfg().getDefaultInverseManyToManyConfig(), inverseM2mConfig);
            middleToRight.getToEntity().addRelation(inverseM2m);
        }
    }
1254665
public function getRightRecord(Entity $rightEntity, $foreignKey, $primaryValue)
    {
        if (!$primaryValue) {
            return null;
        }

        if ($this->inheritRightRepository) {
            $rightEntity->setRepository($this->getLeftEntity()->getRepository());
        }
        $entity = $rightEntity->where($foreignKey, $primaryValue);

        /**
         * Add conditions applied on query.
         */
        foreach ($this->getQuery()->getWhere()->getChildren() as $condition) {
            $entity->where(
                function(Parenthesis $parenthesis) use ($condition) {
                    $parenthesis->push($condition);
                }
            );
        }

        foreach ($this->getQuery()->getBinds('where') as $bind) {
            $entity->getQuery()->bind($bind, 'where');
        }
        
        return (new GetRecords($rightEntity))->executeOne();
    }
120667
protected function insertBelongsTo(Model $record, Relation $relation, $columnValue)
    {
        $foreignKeyName = $relation->getForeignKey();
        list($table, $label) = $this->parseRecordLabel($columnValue);
        $foreignKeyValue = $this->generateKey($label, $table);
        $record->$foreignKeyName = $foreignKeyValue;
    }
1170575
public static function setField($owningEntity, $key, CustomFieldBase $entity)
    {
        if ($entity->isEmpty()) {
            self::remove($owningEntity, $key);

            return;
        }
        /** @var Collection */
        $customFields = $owningEntity->getNonemptyCustomFields();
        if ($entity->getFieldId() !== $key) {
            $entity = clone $entity;
            $entity->setFieldId($key);
        }
        $customFields->set($key, $entity);
    }
327573
public static function getValue($owningEntity, $key)
    {
        $entity = $owningEntity->getNonemptyCustomFields()->get($key);

        if ($entity) {
            $value = $entity->getValue();
        } else {
            self::checkCustomFieldExists($owningEntity, $key);
            $value = null;
        }

        return $value;
    }
1015323
public function getByPrimaryKey($primaryKeyValue)
    {
        $this->connectToDB();
        $this->queryBuilder->table($this->view());
        $this->primaryKeyWhere($primaryKeyValue);
        return current($this->queryBuilder->get());
    }
229470
protected function getApiEntity(CollectionInterface $entity, $locale, $entities = null, $breadcrumbEntities = null)
    {
        $apiEntity = new Collection($entity, $locale);

        $children = null;

        if (null !== $entities) {
            $children = [];
            foreach ($entities as $possibleChild) {
                if (null !== ($parent = $possibleChild->getParent()) && $parent->getId() === $entity->getId()) {
                    $children[] = $this->getApiEntity($possibleChild, $locale, $entities);
                }
            }
        }

        $apiEntity->setChildren($children);
        if (null !== $entity->getParent()) {
            $apiEntity->setParent($this->getApiEntity($entity->getParent(), $locale));
        }

        if (null !== $breadcrumbEntities) {
            $this->setBreadcrumbToCollection($apiEntity, $locale, $breadcrumbEntities);
        }

        if ($entity && $entity->getId()) {
            $apiEntity->setMediaCount($this->collectionRepository->countMedia($entity));
            $apiEntity->setSubCollectionCount($this->collectionRepository->countSubCollections($entity));
        }

        return $this->addPreview($apiEntity);
    }
855165
public function load(Connection $connection, array $primaryValues)
    {
        $targetAdapter = $connection->getAdapter($this->targetReflection->getAdapterName());

        if ($this->dominant) {

            $currentAdapter = $connection->getAdapter(
                $this->sourceReflection->getAdapterName()
            );
        } else{
            $currentAdapter = $targetAdapter;
        }

        $joinQuery = $currentAdapter->createSelect(
            $this->joinResource,
            [$this->joinKey, $this->referencingKey]
        );
        $joinQuery->setFilter(
            [$this->joinKey => [Filter::EQUAL => $primaryValues]]
        );

        $joinResult = $currentAdapter->execute($joinQuery);

        if (!$joinResult) {
            return [];
        }

        $joinResult = Association::groupResult(
            $joinResult,
            [$this->referencingKey, $this->joinKey]
        );

        $targetQuery = $targetAdapter->createSelect(
            $this->targetReflection->getAdapterResource()
        );
        $targetQuery->setFilter(
            [
                $this->targetReflection->getPrimaryProperty()->getUnmapped() => [
                    Entity\Filter::EQUAL => array_keys($joinResult)
                ]
            ]
        );

        $targetResult = $targetAdapter->execute($targetQuery);
        if (!$targetResult) {
            return [];
        }

        $targetResult = Association::groupResult(
            $targetResult,
            [$this->targetReflection->getPrimaryProperty()->getUnmapped()]
        );

        $result = [];
        foreach ($joinResult as $targetKey => $join) {

            foreach ($join as $originKey => $data) {
                if (!isset($targetResult[$targetKey])) {
                    throw new AssociationException(
                        "Can not merge associated result key '" . $targetKey
                        . "' not found in result from '"
                        . $this->targetReflection->getAdapterResource()
                        . "'! Maybe wrong value in join resource."
                    );
                }
                $result[$originKey][] = $targetResult[$targetKey];
            }
        }

        return $result;
    }
157438
public function hasOne($entity, string $related, string $foreignKey = null, string $localKey = null): HasOne
    {
        $foreignKey = $foreignKey ?: $this->getForeignKey();

        $relatedMapper = Manager::getInstance()->mapper($related);

        $relatedMap = $relatedMapper->getEntityMap();

        $localKey = $localKey ?: $this->getKeyName();

        // Add the relation to the definition in map
        list(, $caller) = debug_backtrace(false);
        $relation = $caller['function'];
        $this->relatedClasses[$relation] = $related;

        $this->addSingleRelation($relation);
        $this->addForeignRelation($relation);
        $this->addNonProxyRelation($relation);

        // This relationship will always be eager loaded, as proxying it would
        // mean having an object that doesn't actually exists.
        if (!in_array($relation, $this->with)) {
            $this->with[] = $relation;
        }

        return new HasOne($relatedMapper, $entity, /*$relatedMap->getTable().'.'*/$foreignKey, $localKey);
    }
72453
public function belongsTo($entity, string $related, string $foreignKey = null, string $otherKey = null): BelongsTo
    {
        // Add the relation to the definition in map
        list(, $caller) = debug_backtrace(false);
        $relation = $caller['function'];
        $this->relatedClasses[$relation] = $related;

        $this->addSingleRelation($relation);
        $this->addLocalRelation($relation);

        // If no foreign key was supplied, we can use a backtrace to guess the proper
        // foreign key name by using the name of the relationship function, which
        // when combined with an "_id" should conventionally match the columns.
        if (is_null($foreignKey)) {
            $foreignKey = snake_case($relation).'_id';
        }

        $this->localForeignKeys[$relation] = $foreignKey;

        $relatedMapper = Manager::getInstance()->mapper($related);

        $otherKey = $otherKey ?: $relatedMapper->getEntityMap()->getKeyName();

        return new BelongsTo($relatedMapper, $entity, $foreignKey, $otherKey, $relation);
    }
91209
public function read($entityClass, $primaryKey, array $commandOptions = array())
    {
        $entity = $this->initEntity($entityClass, $primaryKey);
        $this->dispatchEntityRequestEvent(Events::ENTITY_PRE_READ, $entity);

        $commandOptions += array(
            'ConsistentRead'         => $this->consistentRead,
            'TableName'              => $this->getEntityTable($entity),
            'Key'                    => $this->formatKeyCondition($entity),
            'ReturnConsumedCapacity' => $this->returnConsumedCapacity,
        );

        $model = $this->dynamoDb->getItem($commandOptions);

        if (isset($model['Item'])) {
            $this->populateEntity($entity, $model['Item']);
            $this->dispatchEntityResponseEvent(Events::ENTITY_POST_READ, $entity, $model);
            return $entity;
        }

        return false;
    }
642703
private void populateCollectionFromJoinTable(Object entity, EntityMetadata entityMetadata,
            PersistenceDelegator delegator, Relation relation)
    {
        JoinTableMetadata jtMetadata = relation.getJoinTableMetadata();
        Client pClient = delegator.getClient(entityMetadata);

        String schema = entityMetadata.getSchema();

        EntityMetadata owningEntityMetadata = KunderaMetadataManager.getEntityMetadata(delegator.getKunderaMetadata(),
                relation.getTargetEntity());
        Class columnJavaType = owningEntityMetadata.getIdAttribute().getJavaType();
        if (jtMetadata == null)
        {
            columnJavaType = entityMetadata.getIdAttribute().getJavaType();
            Relation owningEntityMetadataRelation = owningEntityMetadata.getRelation(relation.getMappedBy());
            jtMetadata = owningEntityMetadataRelation.getJoinTableMetadata();
            pClient = delegator.getClient(owningEntityMetadata);
            schema = owningEntityMetadata.getSchema();
        }

        String joinTableName = jtMetadata.getJoinTableName();

        Set<String> joinColumns = jtMetadata.getJoinColumns();
        Set<String> inverseJoinColumns = jtMetadata.getInverseJoinColumns();

        String joinColumnName = (String) joinColumns.toArray()[0];
        String inverseJoinColumnName = (String) inverseJoinColumns.toArray()[0];

        Object entityId = PropertyAccessorHelper.getId(entity, entityMetadata);
        List<?> foreignKeys = pClient.getColumnsById(schema, joinTableName, joinColumnName, inverseJoinColumnName,
                entityId, columnJavaType);

        List childrenEntities = new ArrayList();

        if (foreignKeys != null)
        {
            for (Object foreignKey : foreignKeys)
            {
                EntityMetadata childMetadata = KunderaMetadataManager.getEntityMetadata(delegator.getKunderaMetadata(),
                        relation.getTargetEntity());

                Object child = delegator.find(relation.getTargetEntity(), foreignKey);
                Object obj = child instanceof EnhanceEntity && child != null ? ((EnhanceEntity) child).getEntity()
                        : child;

                // If child has any bidirectional relationship, process them
                // here
                Field biDirectionalField = relation.getBiDirectionalField();
                boolean isBidirectionalRelation = (biDirectionalField != null);

                if (isBidirectionalRelation && obj != null)
                {
                    Object columnValue = PropertyAccessorHelper.getId(obj, childMetadata);
                    Object[] pKeys = pClient.findIdsByColumn(entityMetadata.getSchema(), joinTableName, joinColumnName,
                            inverseJoinColumnName, columnValue, entityMetadata.getEntityClazz());
                    List parents = delegator.find(entity.getClass(), pKeys);
                    PropertyAccessorHelper.set(obj, biDirectionalField,
                            ObjectUtils.getFieldInstance(parents, biDirectionalField));
                    PersistenceCacheManager.addEntityToPersistenceCache(obj, delegator, columnValue);
                }

                childrenEntities.add(obj);
            }
        }
        Field childField = relation.getProperty();

        try
        {
            PropertyAccessorHelper.set(
                    entity,
                    childField,
                    PropertyAccessorHelper.isCollection(childField.getType()) ? ObjectUtils.getFieldInstance(
                            childrenEntities, childField) : childrenEntities.get(0));
            PersistenceCacheManager.addEntityToPersistenceCache(entity, delegator, entityId);
        }
        catch (PropertyAccessException ex)
        {
            throw new EntityReaderException(ex);
        }
    }