find all records which are related to the same entity
@param  [type] $entity [description]
@param  [type] $enity  [description]
@return [type]         [description]
489721
public function related($entity = NULL, $enity = NULL)
    {
        $this->andWhere(['entity' => $entity, 'entity_id' => $this->entity_id]);
        return $this;
    }
448898
public function processRecords(Entity $entity, array $with, $records, $readOnly)
    {
        $pkField = $entity->getPrimaryKey();

        $objects          = [];
        $currentKey       = null;
        $object           = null;
        $recordsToProcess = [];

        $relations = array_map(
            [$entity, 'getRelation'],
            array_intersect($with, $entity->getRelationNames())
        );

        foreach ($records as $record) {
            //Extract columns that are relevant for the current metadata
            $key = $record[ $pkField ];
            if ($currentKey !== $key) {
                if ($object !== null) {
                    //Process and save the previous object
                    $this->processRelated(
                        $entity,
                        $object,
                        $readOnly,
                        $recordsToProcess,
                        $relations,
                        $with
                    );
                    $recordsToProcess       = [];
                    $objects[ $currentKey ] = $object;
                }
                $currentKey = $key;
                $object     = $this->createObject(
                    $entity,
                    $record,
                    $relations,
                    $readOnly
                );
            }
            //Store the record to be processed for the related entities
            $recordsToProcess[] = $record;
        }
        if ($object !== null) {
            //Process and save the last object
            $this->processRelated(
                $entity,
                $object,
                $readOnly,
                $recordsToProcess,
                $relations,
                $with
            );
            $objects[ $key ] = $object;
        }

        return $objects;
    }
647617
public function checkEntities($entities)
    {
        return array_filter($entities, function ($val) {
            $entityClass = $this->entityClass;
            return ($val instanceof $entityClass);
        });
    }
219687
public function getMentionsFromRelatedEntity($entity) {
    if ($entity->getEntityTypeId() === 'comment') {
      if ($entity->getParentComment()) {
        $entity = $entity->getParentComment();
      }
    }
    // Mention entity can't be loaded at time of new post or comment creation.
    $mentions = \Drupal::entityTypeManager()
      ->getStorage('mentions')
      ->loadByProperties([
        'entity_type' => $entity->getEntityTypeId(),
        'entity_id' => $entity->id(),
      ]);
    return $mentions;
  }
546477
public function load(Entity $entity)
    {
        /** @var \Slick\Orm\Sql\Select $sql */
        $sql = call_user_func_array(
            array($this->getRelatedEntity(), 'find'),
            []
        );
        $pmk = $this->getEntity()->getPrimaryKey();
        $table = Entity\Manager::getInstance()->get($this->getRelatedEntity())
            ->getEntity()->getTableName();
        $sql->where(
            [
                "{$table}.{$this->getForeignKey()} = :id" => [
                    ':id' => $this->getEntity()->$pmk
                ]
            ]
        );
        return $sql->first();
    }
732241
private function cascadeRefresh($entity, array &$visited)
    {
        $class = $this->em->getClassMetadata(get_class($entity));

        $associationMappings = array_filter(
            $class->associationMappings,
            function ($assoc) { return $assoc['isCascadeRefresh']; }
        );

        foreach ($associationMappings as $assoc) {
            $relatedEntities = $class->reflFields[$assoc['fieldName']]->getValue($entity);

            switch (true) {
                case ($relatedEntities instanceof PersistentCollection):
                    // Unwrap so that foreach() does not initialize
                    $relatedEntities = $relatedEntities->unwrap();
                    // break; is commented intentionally!

                case ($relatedEntities instanceof Collection):
                case (is_array($relatedEntities)):
                    foreach ($relatedEntities as $relatedEntity) {
                        $this->doRefresh($relatedEntity, $visited);
                    }
                    break;

                case ($relatedEntities !== null):
                    $this->doRefresh($relatedEntities, $visited);
                    break;

                default:
                    // Do nothing
            }
        }
    }
568720
public function setEntity(Entity $entity)
    {
        /** @var SharedEventManager $events */
        $events = $this->getContainer()->get('sharedEventManager');
        $events->attach(
            get_class($entity),
            Save::BEFORE_SAVE,
            [$this, 'beforeSave']
        );
        $events->attach(
            get_class($entity),
            Select::BEFORE_SELECT,
            [$this, 'beforeSelect']
        );
        $events->attach(
            get_class($entity),
            Select::AFTER_SELECT,
            [$this, 'afterSelect']
        );
        $this->getContainer()->set('sharedEventManager', $events);
        return parent::setEntity($entity);
    }
715101
public function solveFetch(Entity &$entity)
    {
        // We can use the static ::get method on the entity
        $targetEntity = $this->relation->targetEntity;

        return call_user_func($targetEntity . '::get', $entity->{$this->relation->join->column});
    }
1273080
public function isEntity( &$entity = null )
    {
        if( isset( $this->data['entity'] ) ) {
            $entity = $this->data['entity'];
            return true;
        }
        $entity = null;
        return false;
    }
23328
public function hasOne($entity, callable $callback = null, $alias = null)
    {
        $relation = $this->returnRelation(HasOne::class, $entity, $callback, $alias);

        return $relation;
    }
359099
private function matchRelationship(
        Identity $identity,
        object $entity,
        Relationship $meta,
        MapInterface $changeset,
        Query $query
    ): Query {
        $name = $this->name->sprintf(\md5($identity->value()));
        $this->variables = $this->variables->put(
            $name,
            $this->buildProperties(
                $changeset,
                $meta->properties()
            )
        );

        return $query
            ->match()
            ->linkedTo()
            ->through(
                (string) $meta->type(),
                (string) $name
            )
            ->withProperty(
                $meta->identity()->property(),
                (string) $name
                    ->prepend('{')
                    ->append('_identity}')
            )
            ->withParameter(
                (string) $name->append('_identity'),
                $identity->value()
            );
    }
618002
public function page($entity) {
		if ($entity->type !== 'namespace') {
			return false;
		}
		return Pages::find('first', [
			'conditions' => [
				'index' => $entity->index,
				'name' => $entity->name
			]
		]);
	}
969229
public function solveFetch(Entity &$entity)
    {
        // We need to find all target entities with the ID defined in the current entity source column
        $column = $this->relation->join->column;

        $value = $entity->{$column};
        $where = array($this->relation->join->targetColumn => $value);

        $query = EntityManager::find($this->relation->targetEntity);
        return $query->where($where)->all();
    }
1282778
public function save($entity, $options = [])
    {
        if ($this->link() !== static::LINK_KEY) {
            return true;
        }

        $name = $this->name();
        if (!isset($entity->{$name})) {
            return true;
        }

        $conditions = $this->match($entity);
        $related = $entity->{$name};
        $result = !!$related->set($conditions)->save($options);
        return $result;
    }
1049834
public function findByEntityInstance($entity)
    {
        $businessEntity = null;
        $class = new \ReflectionClass($entity);
        while (!$businessEntity && $class && $class->name !== null) {
            $businessEntity = $this->findByEntityClassname($class->name);
            $class = $class->getParentClass();
        }

        return $businessEntity;
    }
248453
public function setEntity(Entity $entity)
    {
        $this->each(
            function(Record $record) use ($entity) {
                $record->setEntity($entity);
                $record->setEntityClass(get_class($entity));
            }
        );

        return $this;
    }
119988
public function fetchAssociatedRepository($entity_property)
	{
		$entity_class       = $this->getClassName();
		$class_meta_data    = $this->getEntityManager()->getClassMetaData($entity_class);
		$associated_mapping = $class_meta_data->getAssociationMapping($entity_property);

		return $this->getEntityManager()->getRepository($associated_mapping['targetEntity']);
	}