与复合唯一约束的关系(symfony + 学说)

Relation with composite unique constraint (symfony + doctrine)

我正在尝试创建外键引用不是主键而是复合唯一约束的关系。 为什么?非规范化数据库架构以减少连接数。

#[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

一切顺利。但是当我尝试将数据添加到 ExchangeRateHistoryType 时 - 错误。 客户代码:

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

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

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

我做错了什么?

Doctrine 的文档:

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.

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