1

Using Doctrine 2 and Symfony 2.7 I want to use an automated count for a column in my db.

Example:
So when I update a report, I want to add the user (which is the parent of the report by a OneToMany relation) to the leaderboards with the column completed set to 1 (setCompleted). When the user was already on the leaderboards, I want to find him and add 1 to the completed tasks value.

    if (!$lb) {
       $new = New Leaderboard();
       $new->setUsers($user)
           ->setCompleted('1');
       $em->persist($new);
   } else {
       $update = $em->getRepository('AppBundle:Leaderboard')->findBy(array('user' => $user));
       $update->setCompleted('2');
   }

So basically I want to automate the $update->setCompleted('2'); so that it takes the current value and adds one to that and then flush that to the database.

I hope this makes any sense? No sure how to explain it or search for it online...

nclsvh
  • 2,628
  • 5
  • 30
  • 52

1 Answers1

0

You could use an onFlush listener to watch your Report entity for updates and increment/create the leaderboard entry depending on the state of the Report.

http://doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/reference/events.html#onflush

Requires a bit of (careful) reading, but it will do what you want.

Here's a couple of questions I answered on more or less the same subject with examples that should get you started pretty quick

Track field changes on Doctrine entity

Persisting other entities inside preUpdate of Doctrine Entity Listener

The basic flow you want is to capture updates to Report (the simpler second example under my answer shows this being done for an entity). Then based on the state of Report, you create a new Leaderboard entity and attach it to Report, OR update the existing Leaderboard entity for that report.

Note it's important to not flush the entity, just add it to the UOW like so

    $this->getEntityManager()->persist($entity);
    $metaData = $this->getEntityManager()->getClassMetadata($className);
    $this->getUnitOfWork()->computeChangeSet($metaData, $entity);

Hope that helps!

Community
  • 1
  • 1
Richard
  • 4,079
  • 1
  • 14
  • 17
  • Great thanks, I'll have a look at it tonight. Do you maybe know a 'quick/dirty' fix for this? I have a deadline for the beta version next week. I want to get this working asap... – nclsvh Dec 14 '15 at 12:15
  • I've added some additional information to my answer! – Richard Dec 14 '15 at 18:45