php – 使用复合主键生成自动增量ID
|
我想给一个实体(发票,订单,预订等)一个唯一的序列号,但在那一年内只是唯一的.因此,每年(或其他字段,如客户)启动的第一张发票的ID为1.这意味着可以有复合主键(年份,ID)或一个主键(即invoice_id)和另外两个列.独特的. 我的问题:使用Doctrine2和Symfony2为对象提供自动生成的ID和其他值的唯一组合的最佳方法是什么? 复合键的学说限制 Doctrine无法为具有复合主键的实体分配自动生成的ID(http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/tutorials/composite-primary-keys.html):
手动设置序列号 所以我必须手动分配ID.为了做到这一点,我试图在某一年寻找最高的ID并给出ID为1的新实体.我怀疑这是最好的方式,即使它是,我也没有找到最好的(DRY) )这样做的方式.由于我认为这是一个通用问题,我想阻止XY-problem,我已经开始提出这个问题了. 香草选择:仅限MyISAM 我找到了基于this answer的’vanilla’MySQL / MyISAM解决方案: CREATE TABLE IF NOT EXISTS `invoice` ( `year` int(1) NOT NULL,`id` mediumint(9) NOT NULL AUTO_INCREMENT,PRIMARY KEY (`year`,`id`) ) ENGINE=MyISAM; 由于Doctrine2的局限性,这是行不通的,所以我正在寻找一个类似于这个vanilla MySQL解决方案的Doctrine ORM. 其他方案 InnoDB也有一个解决方案:Defining Composite Key with Auto Increment in MySQL 您链接的预插入触发器解决方案的ORM等效项将是生命周期回调.你可以阅读更多关于他们 here.一个天真的解决方案看起来像这样. services.yml services:
invoice.listener:
class: MyCompanyCompanyBundleEventListenerInvoiceListener
tags :
- { name: doctrine.event_subscriber,connection: default }
InvoiceListener.php <?php
namespace MyCompanyCompanyBundleEventListener;
use SymfonyComponentEventDispatcherEventDispatcherInterface;
use DoctrineCommonEventSubscriber;
use DoctrineORMEventOnFlushEventArgs;
use DoctrineORMEventPostFlushEventArgs;
use MyCompanyCompanyBundleEntityInvoice;
class InvoiceListener implements EventSubscriber {
protected $invoices;
public function getSubscribedEvents() {
return [
'onFlush','postFlush'
];
}
public function onFlush(OnFlushEventArgs $event) {
$this->invoices = [];
/* @var $em DoctrineORMEntityManager */
$em = $event->getEntityManager();
/* @var $uow DoctrineORMUnitOfWork */
$uow = $em->getUnitOfWork();
foreach ($uow->getScheduledEntityInsertions() as $entity) {
if ($entity instanceof Invoice) {
$this->invoices[] = $entity;
}
}
}
public function postFlush(PostFlushEventArgs $event) {
if (!empty($this->invoices)) {
/* @var $em DoctrineORMEntityManager */
$em = $event->getEntityManager();
foreach ($this->invoices as $invoice) {
// Get all invoices already in the database for the year in question
$invoicesToDate = $em
->getRepository('MyCompanyCompanyBundle:Invoice')
->findBy(array(
'year' => $invoice->getYear()
// You could include e.g. clientID here if you wanted
// to generate a different sequence per client
);
// Add your sequence number
$invoice->setSequenceNum(count($invoicesToDate) + 1);
/* @var $invoice MyCompanyCompanyBundleEntityInvoice */
$em->persist($invoice);
}
$em->flush();
}
}
} (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
