您链接的预插入触发器解决方案的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();
}
}
}