Home > Mobile >  Relation with composite unique constraint (symfony doctrine)
Relation with composite unique constraint (symfony doctrine)

Time:12-08

I'm trying to create relation where foreign key reference NOT to primary key but to composite unique constraint. Why? Denormalize database schema for decrease join's count.

#[ORM\Entity(repositoryClass: CurrencyRepository::class)]
#[ORM\UniqueConstraint(fields: ['slug', 'type'])]
#[UniqueEntity(
    fields: ['type', 'slug'],
    message: 'This slug is already in use on that type.',
    errorPath: 'slug',
)]
class Currency
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column(type: 'integer')]
    private ?int $id;

    #[ORM\Column(type: 'smallint', length: 1)]
    private ?int $type;

    #[ORM\Column(type: 'string', length: 25)]
    private ?string $slug;

    // ...
}
#[ORM\Entity(repositoryClass: ExchangeRateHistoryTypeRepository::class)]
class ExchangeRateHistoryType
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column(type: 'integer')]
    private int $id;

    #[ORM\ManyToOne(targetEntity: Currency::class)]
    #[ORM\JoinColumn(name: 'currency_slug', referencedColumnName: 'slug', nullable: false)]
    #[ORM\JoinColumn(name: 'currency_type', referencedColumnName: 'type', nullable: false)]
    private ?Currency $currency;
php bin/console make:migration
php bin/console doctrine:migrations:migrate

All good. But when i try to add data to ExchangeRateHistoryType - error. Client code:

$exchangeRateHistoryType = new ExchangeRateHistoryType();
$exchangeRateHistoryType->setCurrency($currency);
// ...

$this->entityManager->persist($exchangeRateHistoryType);
$this->entityManager->flush();

In BasicEntityPersister.php line 674: Warning: Undefined array key "slug"

What i'm doing wrong?

CodePudding user response:

Doctrine's documentation:

It is not possible to use join columns pointing to non-primary keys. Doctrine will think these are the primary keys and create lazy-loading proxies with the data, which can lead to unexpected results. Doctrine can for performance reasons not validate the correctness of this settings at runtime but only through the Validate Schema command.

Source: https://www.doctrine-project.org/projects/doctrine-orm/en/2.10/reference/limitations-and-known-issues.html#join-columns-with-non-primary-keys

  • Related