Добавляет пользовательское поле к объекту если его не существует
@param $entityId
@param $fieldName
@param $fields
@return int
@throws \Sprint\Migration\Exceptions\HelperException
175993
public function addUserTypeEntityIfNotExists($entityId, $fieldName, $fields) {
        $item = $this->getUserTypeEntity($entityId, $fieldName);
        if ($item) {
            return $item['ID'];
        }

        return $this->addUserTypeEntity($entityId, $fieldName, $fields);
    }
15593
protected function getHelpForImage($entity, $fieldName)
    {
        $container        = $this->getConfigurationPool()->getContainer();
        $annotationReader = $container->get('annotation_reader');

        $reflectionClass = new \ReflectionClass(get_class($entity));
        $annotation = $annotationReader->getPropertyAnnotation($reflectionClass->getProperty($fieldName), Image::class);
        $imageHelp = sprintf('Допустимый размер %s*%s', $annotation->minWidth, $annotation->minHeight);

        return $imageHelp;
    }
1339681
public function getCount(EntityManager $em, Request $request)
	{
		$stmt = $this->buildCountQuery($em, $request);
		$stmt->execute();
		return (int) $stmt->fetchColumn();
	}
1228175
public function updateOne($moduleName, $entityID, array $params)
    {
        if (!is_assoc_array($params)) {
            throw new WSException(
                "You have to specify at least one search parameter (prop => value) 
                in order to be able to update the entity(ies)"
            );
        }

        // Fail if no ID was supplied
        if (empty($entityID)) {
            throw new WSException("The list of contraints must contain a valid ID");
        }

        // Preprend so-called moduleid if needed
        $entityID = $this->wsClient->modules->getTypedID($moduleName, $entityID);

        // Check if the entity exists + retrieve its data so it can be used below
        $entityData = $this->findOneByID($moduleName, $entityID);
        if ($entityData === false && !is_array($entityData)) {
            throw new WSException("Such entity doesn't exist, so it cannot be updated");
        }

        // The new data overrides the existing one needed to provide
        // mandatory field values to WS 'update' operation
        $params = array_merge(
            $entityData,
            $params
        );

        $requestData = [
            'elementType' => $moduleName,
            'element'     => json_encode($params)
        ];

        return $this->wsClient->invokeOperation('update', $requestData);
    }
260797
public function save(string $fieldname, array $config, EntityInterface $entity = null)
    {
        if (!empty($entity[$config['name']])) {
            $assocData = $entity[$config['name']];
            if (is_array($assocData)) {
                $data = [];
                foreach ($assocData as $assocEntity) {
                    $entityTable = TableRegistry::get($assocEntity->source());
                    $data[] = $assocEntity->{$entityTable->displayField()};
                }

                return $data;
            }
        }

        return $entity[$config['name']];
    }
463209
public function setFieldsToEntity(string $entityFqn, array $fieldFqns): self
    {
        foreach ($fieldFqns as $fieldFqn) {
            $this->fieldSetter->setEntityHasField($entityFqn, $fieldFqn);
        }

        return $this;
    }
1030701
public function deleteOne($moduleName, $entityID)
    {
        // Preprend so-called moduleid if needed
        $entityID = $this->wsClient->modules->getTypedID($moduleName, $entityID);
        return $this->wsClient->invokeOperation('delete', [ 'id' => $entityID ]);
    }
951877
protected function correctFields($entityName, array $ormMetadata)
    {
        $entityDefs = $this->getEntityDefs();

        $entityMetadata = $ormMetadata[$entityName];
        //load custom field definitions and customCodes
        foreach ($entityMetadata['fields'] as $fieldName => $fieldParams) {
            if (empty($fieldParams['type'])) continue;

            $fieldType = ucfirst($fieldParams['type']);
            $className = '\Espo\Custom\Core\Utils\Database\Orm\Fields\\' . $fieldType;
            if (!class_exists($className)) {
                $className = '\Espo\Core\Utils\Database\Orm\Fields\\' . $fieldType;
            }

            if (class_exists($className) && method_exists($className, 'load')) {
                $helperClass = new $className($this->metadata, $ormMetadata, $entityDefs);
                $fieldResult = $helperClass->process($fieldName, $entityName);
                if (isset($fieldResult['unset'])) {
                    $ormMetadata = Util::unsetInArray($ormMetadata, $fieldResult['unset']);
                    unset($fieldResult['unset']);
                }

                $ormMetadata = Util::merge($ormMetadata, $fieldResult);
            }

            $defaultAttributes = $this->metadata->get(['entityDefs', $entityName, 'fields', $fieldName, 'defaultAttributes']);
            if ($defaultAttributes && array_key_exists($fieldName, $defaultAttributes)) {
                $defaultMetadataPart = array(
                    $entityName => array(
                        'fields' => array(
                            $fieldName => array(
                                'default' => $defaultAttributes[$fieldName]
                            )
                        )
                    )
                );
                $ormMetadata = Util::merge($ormMetadata, $defaultMetadataPart);
            }
        }

        //todo move to separate file
        //add a field 'isFollowed' for scopes with 'stream => true'
        $scopeDefs = $this->getMetadata()->get('scopes.'.$entityName);
        if (isset($scopeDefs['stream']) && $scopeDefs['stream']) {
            if (!isset($entityMetadata['fields']['isFollowed'])) {
                $ormMetadata[$entityName]['fields']['isFollowed'] = array(
                    'type' => 'varchar',
                    'notStorable' => true,
                    'notExportable' => true,
                );

                $ormMetadata[$entityName]['fields']['followersIds'] = array(
                    'type' => 'jsonArray',
                    'notStorable' => true,
                    'notExportable' => true,
                );
                $ormMetadata[$entityName]['fields']['followersNames'] = array(
                    'type' => 'jsonObject',
                    'notStorable' => true,
                    'notExportable' => true,
                );
            }
        } //END: add a field 'isFollowed' for stream => true

        return $ormMetadata;
    }
244607
public function getRecord($tableName, $field, $value, $fields = array())
    {
        try {
            return $this->db->getRecord($tableName, $field, $value, $fields);
        } catch (\Exception $e) {
            throw new DbException($e->getMessage());
        }
    }
1189560
private function processField(Comment $comment, $property, Entity $entity)
    {
        /** @var \ORMiny\Annotations\Field $fieldAnnotation */
        $fieldAnnotation = current($comment->getAnnotationType(FieldAnnotation::class));

        if ($fieldAnnotation->name === null) {
            $fieldAnnotation->name = $property;
        }

        $field = new Field(
            $this->createSetter($entity, $property, $fieldAnnotation),
            $this->createGetter($entity, $property, $fieldAnnotation)
        );

        $fieldName = $entity->addField($fieldAnnotation->name, $field);

        if ($comment->has('Id')) {
            if ($entity->getPrimaryKey() !== null) {
                throw new EntityDefinitionException("Compound primary key is not supported.");
            }
            $entity->setPrimaryKey($fieldName);
        }
    }
688231
protected function lookUpEntity($entityId) {
        $entity = $this->generateEntity();
        $entityInstance = $entity->findFirst($entityId);
        if($entityInstance === false) {
            throw new Exception("Invalid Entity Id: Entity not found.", 404);
        }
        return $entityInstance;
    }
160500
public function count($field = '*')
    {
        if ($field !== '*' && !in_array($field, $this->getFields())) {
            throw new \DomainException(__METHOD__ . '|Field is not allowed ! (field: ' . $field . ')');
        }

        $query = 'SELECT COUNT(' . $field . ') AS NB_RESULTS FROM ' . $this->table . ' ' . $this->getQueryWhere();

        $statement = $this->db->prepare($query);
        $statement->execute($this->binds);

        $this->clear();

        return (int) $statement->fetchColumn(0);
    }
601322
public function setFieldValue($entity, $fieldName, $value)
    {
        if ($this->fieldMappings[$fieldName]['direct']) {
            $this->reflFields[$fieldName]->setValue($entity, $value);
        } else {
            if (!array_key_exists('setMethod', $this->fieldMappings[$fieldName])) {
                $this->fieldMappings[$fieldName]['setMethod'] = $this->inferSetter($fieldName);
            }
            $setter = $this->fieldMappings[$fieldName]['setMethod'];

            if ($this->reflClass->hasMethod($setter)) {
                return call_user_func(array($entity, $setter), $value);
            } else {
                throw MappingException::fieldSetMethodDoesNotExist($this->name, $fieldName, $setter);
            }
        }
    }
577756
public function getNewMaxId($entityClassname): int
    {
        $maxId = $this->em->createQueryBuilder()
            ->select('MAX(e.id) + 1')
            ->from($entityClassname, 'e')
            ->getQuery()
            ->getSingleScalarResult();
        return (int) $maxId;
    }
536631
public static function findField($fieldsList, $fieldId)
    {
        $fields = self::filterFieldList($fieldsList, $fieldId);

        if (1 != count($fields)) {
            return null;
        }

        return array_shift($fields);
    }
788624
public function getTranslation(
        $entityType,
        $entityId,
        $entityField,
        $locale
    ) {
        $translation = $this
            ->entityTranslationRepository
            ->findOneBy([
                'entityType' => $entityType,
                'entityId' => $entityId,
                'entityField' => $entityField,
                'locale' => $locale,
            ]);

        return $translation instanceof EntityTranslationInterface
            ? $translation->getTranslation()
            : '';
    }
1312742
protected function updateField(Entity $entity, $field) {
		if ($entity->dirty($field)) {
			return;
		}

		$entity->set($field, $this->getUserId());
	}