Good day to all!

Faced the following task: I have a certain Model Model, with a property that changes over time (history). I need to keep these changes in history in order to use it for statistics in the future. To store the entire history in the database, I decided that it would be reasonable to specify the type for the history property - json_array. And store this story in one cell in the database itself.

Accordingly, the question is: Now, every time I change a property, I need to create an object, get the current value of history get the current array, add a new value to it, save the array. This is done with the following code:

$entity = $em->getRepository('AppBundle:Model')->find($id); $history = $entity->getHistory(); $history[date('Ymd H:i:s')] = $currentValue; $entity->setHistory(); $em->persist($entity); $em->flush(); 

I feel that this is a perversion. Is it possible to somehow solve this problem using Symfony and Doctrine?

Thank you in advance!

  • That you keep the story in the array for nothing - etki
  • @Etki to be honest, in my case I did not come up with a better option. - kover-samolet
  • And how would you advise to keep the story? In a separate table? - kover-samolet
  • Yes, so you run the risk of starting to operate with large amounts of data (for each record and reading of a large array). Strictly speaking, this is not a fact that it will be noticeable, but as the rule of thumb - you should always limit the amount of data. - etki

1 answer 1

So add in the model AppBundle:Model new method, like:

 public function saveValueIntoHistory($currentValue) { $this->history[date('Ymd H:i:s')] = $currentValue; } 

And already in the action game will be:

 $entity = $em->getRepository('AppBundle:Model')->find($id); $entity->saveValueIntoHistory(currentValue); $em->flush(); 

The invocation of the persist method is deliberately missed here, since after receiving the entity from the database, it is already traceable in Doctrine. You need to call persist only if you want to create a new entity that is not yet in the database. And if you first got it to find it, then the extra persist only check for the presence of this object in the Doctrine container.

  • Special thanks for the comment about persist. I did not know about this nuance. - kover-samolet