【问题标题】:Relation with composite unique constraint (symfony + doctrine)与复合唯一约束的关系(symfony + 学说)
【发布时间】:2022-01-11 02:52:03
【问题描述】:

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

#[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();

在 BasicEntityPersister.php 第 674 行:警告:未定义的数组键“slug”

我做错了什么?

【问题讨论】:

    标签: symfony doctrine


    【解决方案1】:

    Doctrine 的文档:

    不能使用指向非主键的连接列。 Doctrine 会认为这些是主键并使用数据创建延迟加载代理,这可能会导致意外结果。出于性能原因,Doctrine 不能在运行时验证此设置的正确性,而只能通过 Validate Schema 命令。

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

    【讨论】:

      猜你喜欢
      • 2014-09-27
      • 2014-09-27
      • 2017-12-05
      • 2016-04-12
      • 1970-01-01
      • 2012-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多