2012-07-25 59 views
2

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

例如:

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的键定义为是“的原因也有我们的web应用程序,这会盲目服用一排,只改变id_azienda或id_sede或revisione_documento,然后重新插入,通过这种方式,该行将是有效的,因为如果主键仅为id_consumo,则不会。

我们正在考虑开始使用doctrine 2进行数据库管理,但是我不明白文档如何实现这样一个实体,如果它是可能的话。

回答

2

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

与复合键不能使用其他 比“分配”,一个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; 
} 
+0

你会如何建议做自动增量实现?由于我们的数据库是MySQL,所以我可以像'SELECT MAX(id_consumo)FROM gen_5_23_consumi'这样做,然后在结果中加上1,但这仍然不可取,是吧? '因为在此期间可能会有另一个插入更改最后一个ID .. – 2012-07-26 06:55:31

+0

我更新了答案更清楚。您可以从文档中查看示例。 D2会关注数据的一致性,因为每次刷新都在一个事务中。 – WizardZ 2012-07-26 19:38:18

+0

我会按照您的建议检查文档,感谢您的建议=) – 2012-07-27 06:52:20

0

截至目前你不能做复合材料(小学,国外)键与AUTO INCREMENT选项。

您将不得不使用自己的代码从表格中选择MAX密钥。

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