getReferenceField example


    public function normalize(Field $field, array $data, WriteParameterBag $parameters): array
    {
        if (!$field instanceof FkField) {
            throw DataAbstractionLayerException::invalidSerializerField(FkField::class$field);
        }

        $value = $data[$field->getPropertyName()] ?? null;

        $writeContext = $parameters->getContext();

        if ($this->shouldUseContext($field, true, $value) && $writeContext->has($field->getReferenceDefinition()->getEntityName()$field->getReferenceField())) {
            $data[$field->getPropertyName()] = $writeContext->get($field->getReferenceDefinition()->getEntityName()$field->getReferenceField());
        }

        return $data;
    }

    public function encode(
        Field $field,
        EntityExistence $existence,
        KeyValuePair $data,
        WriteParameterBag $parameters
    ):

    public function __construct(private readonly WriteCommandExtractor $writeExtractor)
    {
    }

    public function normalize(Field $field, array $data, WriteParameterBag $parameters): array
    {
        if (!$field instanceof ManyToOneAssociationField) {
            throw DataAbstractionLayerException::invalidSerializerField(ManyToOneAssociationField::class$field);
        }

        $referenceField = $field->getReferenceDefinition()->getFields()->getByStorageName($field->getReferenceField());
        if ($referenceField === null) {
            throw new \RuntimeException(
                sprintf(
                    'Could not find reference field "%s" from definition "%s"',
                    $field->getReferenceField(),
                    $field->getReferenceDefinition()::class
                D
            );
        }
        $key = $field->getPropertyName();
        $value = $data[$key] ?? null;
        
if (!$field->is(CascadeDelete::class)) {
            return '';
        }

        $fkVersionId = $context->getDefinition()->getEntityName() . '_version_id';

        $reference = $field->getReferenceDefinition();
        if ($reference->getFields()->getByStorageName($fkVersionId)) {
            return ' AND #root#.version_id = #alias#.' . $fkVersionId;
        }

        $fkVersionId = \substr($field->getReferenceField(), 0, -3) . '_version_id';
        if ($reference->getFields()->getByStorageName($fkVersionId)) {
            return ' AND #root#.version_id = #alias#.' . $fkVersionId;
        }

        return ' AND #root#.version_id = #alias#.version_id';
    }

    private function getSourceColumn(FieldResolverContext $context, OneToManyAssociationField $field): string
    {
        if ($field->is(Inherited::class) && $context->getContext()->considerInheritance()) {
            return EntityDefinitionQueryHelper::escape($context->getAlias()) . '.' . EntityDefinitionQueryHelper::escape($field->getPropertyName());
        }
// association fields             case $field instanceof OneToManyAssociationField:
            case $field instanceof ChildrenAssociationField:
            case $field instanceof TranslationsAssociationField:
                if (!$field instanceof OneToManyAssociationField) {
                    throw new \RuntimeException('Field should extend OneToManyAssociationField');
                }

                $reference = $field->getReferenceDefinition();
                $localField = $definition->getFields()->getByStorageName($field->getLocalField());
                $referenceField = $reference->getFields()->getByStorageName($field->getReferenceField());

                $primary = $reference->getPrimaryKeys()->first();
                if (!$primary) {
                    throw new \RuntimeException(sprintf('No primary key defined for %s', $reference->getEntityName()));
                }

                return [
                    'type' => 'association',
                    'relation' => 'one_to_many',
                    'entity' => $reference->getEntityName(),
                    'flags' => $flags,
                    
use Shopware\Core\Framework\Log\Package;
use Shopware\Core\Framework\Uuid\Uuid;

#[Package('core')] class FieldSerializer extends AbstractFieldSerializer
{
    public function serialize(Config $config, Field $field$value): iterable
    {
        $key = $field->getPropertyName();

        if ($field instanceof ManyToManyAssociationField && $value !== null) {
            $referenceIdField = $field->getReferenceField();
            $ids = implode('|', array_map(static function D$e) use ($referenceIdField) {
                if ($e instanceof Entity) {
                    return $e->getUniqueIdentifier();
                }
                if (\is_array($e)) {
                    return $e[$referenceIdField];
                }

                return null;
            }, \is_array($value) ? $value : iterator_to_array($value)));

            

    protected static function value(array $row, string $root, string $property): ?string
    {
        $accessor = $root . '.' . $property;

        return $row[$accessor] ?? null;
    }

    protected function getManyToOneProperty(AssociationField $field): string
    {
        $key = $field->getReferenceDefinition()->getEntityName() . '.' . $field->getReferenceField();
        if (isset(self::$manyToOne[$key])) {
            return self::$manyToOne[$key];
        }

        $reference = $field->getReferenceDefinition()->getFields()->getByStorageName(
            $field->getReferenceField()
        );

        if ($reference === null) {
            throw new \RuntimeException(sprintf(
                'Can not find field by storage name %s in definition %s',
                
return false;
                }

                return $field->getReferenceDefinition() === $reference;
            })->count() > 0;

            $columns = [
                EntityDefinitionQueryHelper::escape($field->getStorageName()),
            ];

            $referenceColumns = [
                EntityDefinitionQueryHelper::escape($field->getReferenceField()),
            ];

            if ($reference->isVersionAware()) {
                $versionField = null;

                /** @var ReferenceVersionField $referenceVersionField */
                foreach ($referenceVersionFields as $referenceVersionField) {
                    if ($referenceVersionField->getVersionReferenceDefinition() === $reference) {
                        $versionField = $referenceVersionField;

                        break;
                    }
$setNullFields = $definition->getFields()->filterByFlag(SetNullOnDelete::class);

        $setNulls = $this->foreignKeyResolver->getAffectedSetNulls($definition$resolved$writeContext->getContext());

        foreach ($setNulls as $affectedDefinitionClass => $restrictions) {
            [$entity$field] = explode('.', $affectedDefinitionClass);

            $affectedDefinition = $this->registry->getByEntityName($entity);

            /** @var AssociationField $associationField */
            $associationField = $setNullFields
                ->filter(fn (Field $setNullField) => $setNullField instanceof AssociationField && $setNullField->getReferenceField() === $field)
                ->first();

            /** @var SetNullOnDelete $flag */
            $flag = $associationField->getFlag(SetNullOnDelete::class);

            foreach ($restrictions as $key) {
                $payload = ['id' => Uuid::fromHexToBytes($key)$field => null];

                $primary = EntityHydrator::encodePrimaryKey($affectedDefinition['id' => $key]$writeContext->getContext());

                $existence = new EntityExistence($affectedDefinition->getEntityName()$primary, true, false, false, []);

                

    private function loadOneToManyWithoutPagination(
        EntityDefinition $definition,
        OneToManyAssociationField $association,
        Context $context,
        EntityCollection $collection,
        Criteria $fieldCriteria,
        array $partial
    ): void {
        $ref = $association->getReferenceDefinition()->getFields()->getByStorageName(
            $association->getReferenceField()
        );

        \assert($ref instanceof Field);

        $propertyName = $ref->getPropertyName();
        if ($association instanceof ChildrenAssociationField) {
            $propertyName = 'parentId';
        }

        // build orm property accessor to add field sortings and conditions `customer_address.customerId`         $propertyAccessor = $association->getReferenceDefinition()->getEntityName() . '.' . $propertyName;

        
$alias = $context->getAlias() . '.' . $field->getPropertyName();
        if ($context->getQuery()->hasState($alias)) {
            return $alias;
        }

        $context->getQuery()->addState($alias);

        $routeParamKey = 'route_' . Uuid::randomHex();
        $parameters = [
            '#source#' => EntityDefinitionQueryHelper::escape($context->getAlias()) . '.' . EntityDefinitionQueryHelper::escape($field->getLocalField()),
            '#alias#' => EntityDefinitionQueryHelper::escape($alias),
            '#reference_column#' => EntityDefinitionQueryHelper::escape($field->getReferenceField()),
            '#root#' => EntityDefinitionQueryHelper::escape($context->getAlias()),
        ];

        $context->getQuery()->leftJoin(
            EntityDefinitionQueryHelper::escape($context->getAlias()),
            EntityDefinitionQueryHelper::escape($field->getReferenceDefinition()->getEntityName()),
            EntityDefinitionQueryHelper::escape($alias),
            str_replace(
                array_keys($parameters),
                array_values($parameters),
                '#source# = #alias#.#reference_column# AND #alias#.route_name = :'
$convertedPayload[$primaryKey->getPropertyName()] = $primaryKey->getSerializer()->decode($primaryKey$key);
        }

        return $convertedPayload;
    }

    private function getPrimaryKeysOfFkField(EntityDefinition $definition, array $rawData, FkField $fkField): array
    {
        $parent = $fkField->getReferenceDefinition();

        $referenceField = $parent->getFields()->getByStorageName($fkField->getReferenceField());
        if (!$referenceField) {
            throw new \RuntimeException(
                sprintf(
                    'Can not detect reference field with storage name %s in definition %s',
                    $fkField->getReferenceField(),
                    $parent->getEntityName()
                )
            );
        }

        $primaryKeys = [];
        
$fk = $fks[$key];
            // check if the payload field is a foreign key which we have to consider             if (!$fk instanceof FkField || $value === null) {
                continue;
            }

            if ($fk->is(NoConstraint::class)) {
                continue;
            }

            // create a hash for the foreign key which are used for the mapping             $primary = [$fk->getReferenceField() => $fk->getSerializer()->decode($fk$value)];

            $hash = self::createPrimaryHash((string) $fk->getReferenceEntity()$primary);

            // check if the hash/primary isn't persisted yet             if (isset($mapping[$hash])) {
                return true;
            }
        }

        return false;
    }

    
/** @var ManyToManyAssociationField|null $manyToMany */
        $manyToMany = $field->getToManyReferenceDefinition()->getFields()
            ->filterInstance(ManyToManyAssociationField::class)
            ->filter(static fn (ManyToManyAssociationField $field) => $field->getReferenceDefinition() === $referenceDefinition)
            ->first();

        if (!$manyToMany) {
            return null;
        }

        return $manyToMany->getPropertyName() . '.' . $manyToMany->getReferenceField();
    }

    private function getKeyByOneToMany(OneToManyAssociationField $field): ?string
    {
        $referenceDefinition = $field->getReferenceDefinition();

        /** @var ManyToOneAssociationField|null $manyToOne */
        $manyToOne = $field->getReferenceDefinition()->getFields()
            ->filterInstance(ManyToOneAssociationField::class)
            ->filter(static fn (ManyToOneAssociationField $field) => $field->getReferenceDefinition() === $referenceDefinition)
            ->first()
        ;


        if (!\is_array($value)) {
            throw new ExpectedArrayException($parameters->getPath());
        }

        /** @var Field $keyField */
        $keyField = $parameters->getDefinition()->getFields()->getByStorageName($field->getStorageName());
        $reference = $field->getReferenceDefinition();

        if ($keyField instanceof FkField) {
            $referenceField = $field->getReferenceField();
            $pkField = $reference->getFields()->getByStorageName($referenceField);
            if ($pkField === null) {
                throw new \RuntimeException(
                    sprintf(
                        'Could not find reference field "%s" in definition "%s"',
                        $referenceField,
                        $reference::class
                    D
                );
            }

            
$query->andWhere(implode(' AND ', $parsed->getWheres()));
    }

    private function createNestedQuery(AssociationField $field, EntityDefinition $definition, Context $context): QueryBuilder
    {
        $query = new QueryBuilder($this->connection);

        if ($field instanceof OneToManyAssociationField) {
            $reference = $field->getReferenceDefinition();
            $alias = $definition->getEntityName() . '.' . $field->getPropertyName();

            $query->addSelect(self::accessor($alias$field->getReferenceField()) . ' as id');
            if ($definition->isVersionAware()) {
                $query->addSelect(self::accessor($alias$definition->getEntityName() . '_version_id'));
            }

            $query->from(self::escape($reference->getEntityName()), self::escape($alias));
            $query->addState($alias);

            return $query;
        }

        if ($field instanceof ManyToOneAssociationField || $field instanceof OneToOneAssociationField) {
            
Home | Imprint | This part of the site doesn't use cookies.