在非相关表中插入数据 - Symfony2和Doctirne2

I am building some business application and lets say there are two tables Orders and MonthlyReports .
These tables are not directly related (there is no relationship between them defined in ORM).
Table MonthlyReports stores total amount of all orders and it should be updated after each purchase that is recorded in Orders table.

I planned to use EventListener postPersist() to automatically change the value of total amount in MonthlyReports, but I face this problem:

  • Doctrine doesn't allow inserting new entities beside using persist() method, and MonthlyReports can't be persisted since it is not related to Orders table


So my question is how to create a new report at the beginning of each month, should I create some fake relationship between these tables to be able to persist new monthly report?

MonthlyReports can't be persisted since it is not related to Orders table

Doctrine events aren't coupled to specific entities and their relationships. You can define a listener to do whatever you want.

<service id="your_namespace.entity.listener.monthly_report_recalculator" class="Your\NamespaceBundle\EventListener\MonthylReportRecalculator">
    <tag name="doctrine.event_listener" event="prePersist" method="prePersist" priority="80" />

    <call method="setContainer">
        <argument type="service" id="service_container" />
    </call>
</service>

Note, if your injecting repositories into an doctrine event listener, you unfortunately will have to grab it from the container if you want to avoid a cyclical dependency.

<?php

namespace Your\NamespaceBundle\EventListener;

use Doctrine\ORM\Event\LifecycleEventArgs;
use Symfony\Component\DependencyInjection\ContainerInterface;

class MonthylReportRecalculator
{
    /**
     * @var \Symfony\Component\DependencyInjection\ContainerInterface
     */
    private $container;

    /**
     * Define Container
     *
     * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
     */
    public function setContainer(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function prePersist(LifecycleEventArgs $event)
    {
        $entity = $event->getEntity();

        if ( ! $entity instanceof Order) {
            return;
        }

        // grab the report repository from container
        // update your report entity
        // save via repository
    }
}

I would also suggest you define a collection of Order entities within your Report entity for auditing purposes.