php中怎么让主键自增长,php – 使用复合主键生成自动增量ID

该博客介绍了如何在Symfony应用中使用Doctrine ORM的生命周期回调来模拟数据库触发器的行为。通过监听`onFlush`和`postFlush`事件,实现在插入发票时自动为每张发票分配唯一的序列号。首先,在服务配置中注册监听器,然后在监听器内部获取即将插入的发票,并在所有插入操作完成后更新序列号。
摘要由CSDN通过智能技术生成

您链接的预插入触发器解决方案的ORM等效项将是生命周期回调.你可以阅读更多关于他们

here.

一个天真的解决方案看起来像这样.

services.yml

services:

invoice.listener:

class: MyCompany\CompanyBundle\EventListener\InvoiceListener

tags :

- { name: doctrine.event_subscriber, connection: default }

InvoiceListener.php

namespace MyCompany\CompanyBundle\EventListener;

use Symfony\Component\EventDispatcher\EventDispatcherInterface;

use Doctrine\Common\EventSubscriber;

use Doctrine\ORM\Event\OnFlushEventArgs;

use Doctrine\ORM\Event\PostFlushEventArgs;

use MyCompany\CompanyBundle\Entity\Invoice;

class InvoiceListener implements EventSubscriber {

protected $invoices;

public function getSubscribedEvents() {

return [

'onFlush',

'postFlush'

];

}

public function onFlush(OnFlushEventArgs $event) {

$this->invoices = [];

/* @var $em \Doctrine\ORM\EntityManager */

$em = $event->getEntityManager();

/* @var $uow \Doctrine\ORM\UnitOfWork */

$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 \Doctrine\ORM\EntityManager */

$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 \MyCompany\CompanyBundle\Entity\Invoice */

$em->persist($invoice);

}

$em->flush();

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值