5

在我们的数据库中,我们的表没有单个自动增量主键,而是一个复合主键,它可能包含也可能不包含自动增量字段作为该主键的第一个字段。

例如:

DROP TABLE IF EXISTS `gen_5_23`;
CREATE TABLE IF NOT EXISTS `gen_5_23` (
    `id_azienda` int(10) unsigned NULL DEFAULT 1,
    `id_sede` int(10) unsigned NULL DEFAULT 1,
    `revisione_documento` int(10) unsigned NULL DEFAULT 0,
    `premessa_generale` text,
    `flag_stampa` char(1) DEFAULT 'N',
    PRIMARY KEY (`id_azienda`,`id_sede`,`revisione_documento`),
    CONSTRAINT `fk_revisione_documento_gen_5_23` FOREIGN KEY (`revisione_documento`, `id_azienda`, `id_sede`) REFERENCES `agews_revisioni_documenti` (`revisione_documento`, `id_azienda`, `id_sede`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS `gen_5_23_consumi`;
CREATE TABLE IF NOT EXISTS `gen_5_23_consumi` (
    `id_consumo` int(10) unsigned AUTO_INCREMENT,
    `id_azienda` int(10) unsigned NULL DEFAULT 1,
    `id_sede` int(10) unsigned NULL DEFAULT 1,
    `revisione_documento` int(10) unsigned NULL DEFAULT 0,
    `consumo` varchar(255) NULL DEFAULT NULL,
    `unita` varchar(255) NULL DEFAULT NULL,
    `valore` float(11,2) NULL DEFAULT 0,
    PRIMARY KEY (id_consumo,`id_azienda`,`id_sede`,`revisione_documento`),
    CONSTRAINT `fk_main_gen_5_23_consumi` FOREIGN KEY (`id_azienda`, `id_sede`, `revisione_documento`) REFERENCES `gen_5_23` (`id_azienda`, `id_sede`, `revisione_documento`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

gen_5_23_consumi 中的键被定义为'因为我们的 webapp 中有一些程序会盲目地取一行,只更改 id_azienda 或 id_sede 或 revisione_documento 然后重新插入它,这样该行将是有效的,因为它不会如果主键只有 id_consumo。

我们正在考虑开始使用原则 2 进行数据库管理,但我从文档中不明白如果可能的话,您将如何实现这样的实体。

4

2 回答 2

3

这是可能的,但不是开箱即用的。您可以将复合键作为实体的主键:http: //docs.doctrine-project.org/projects/doctrine-orm/en/latest/tutorials/composite-primary-keys.html但应该完成自动增量实现在你的代码中,因为

每个具有复合键的实体都不能使用“ASSIGNED”以外的 id 生成器。这意味着必须在调用 EntityManager#persist($entity) 之前设置 ID 字段的值。

要模拟自动增量行为,您可以将带有 id 的序列表作为自动增量 PK 并为此表创建一个实体。将关系从主实体添加到表示自动递增序列的实体,请参阅上面页面中的 ArticleAttribute 类,您的代码应该非常相似:

Class Gen523consumiAuto
{
    /** @Id @Column(type="integer") @GeneratedValue */
    private $id;
}

Class Gen523consumi
{
    /** @Id @OneToOne(targetEntity="Gen523consumiAuto") */
    private $idConsumo;

    /** @Id @Column(type="integer") */
    private $idAzienda;

    /** @Id @Column(type="integer") */
    private $idSede;

    /** @Id @Column(type="integer") */
    private $revisioneDocumento;
}
于 2012-07-25T22:41:25.553 回答
0

到目前为止,您无法使用 AUTO INCREMENT 选项执行复合(主、外)键。

您必须使用自己的代码从表中选择 MAX Key。

然后在您的实体 ID 上设置 MAX + 1。

于 2016-09-06T15:37:18.243 回答