具有自动增量的 Doctrine 2 复合主键

Mat*_*ari 5 php doctrine-orm

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

例如:

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;
Run Code Online (Sandbox Code Playgroud)

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

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

Wiz*_*rdZ 3

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

\n\n
\n

每个具有复合键的实体都不能使用 \n \n \xe2\x80\x9cASSIGNED\xe2\x80\x9d 之外的 id 生成器。这意味着在调用 EntityManager#persist($entity) 之前,必须先设置 ID 字段的值。

\n
\n\n

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

\n\n
Class Gen523consumiAuto\n{\n    /** @Id @Column(type="integer") @GeneratedValue */\n    private $id;\n}\n\nClass Gen523consumi\n{\n    /** @Id @OneToOne(targetEntity="Gen523consumiAuto") */\n    private $idConsumo;\n\n    /** @Id @Column(type="integer") */\n    private $idAzienda;\n\n    /** @Id @Column(type="integer") */\n    private $idSede;\n\n    /** @Id @Column(type="integer") */\n    private $revisioneDocumento;\n}\n
Run Code Online (Sandbox Code Playgroud)\n