php中 复合主键的作用,php-具有自动增量的Doctrine 2复合主键

本文探讨如何在Doctrine ORM中处理没有单一自动递增主键的复合键表,介绍了如何遵循准则2,通过创建辅助实体和OneToOne关系来模拟自动增长ID的行为。实例分析了`gen_5_23_consumi`表的设计和迁移策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

例如:

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或versione_documento然后重新插入它,因此该行将是有效的,因为它不会如果主键只是id_consumo.

我们正在考虑开始使用准则2进行数据库管理,但是从文档中我无法理解,如果可能的话,您将如何实现这样的实体.

解决方法:

Every entity with a composite key cannot use an id generator other

than “ASSIGNED”. That means the ID fields have to have their values

set before you call EntityManager#persist($entity).

要模拟自动增量行为,可以将id为自动增量PK的序列表并为该表创建一个实体.将主要实体之间的关系添加到代表自动递增序列的实体,请参见上页的ArticleArticle类,您的代码应非常相似:

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;

}

标签:doctrine-orm,php

来源: https://codeday.me/bug/20191201/2077568.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值