Doctrine2 and database-side triggers for denormalized fields

Go To StackoverFlow.com

2

Let's say I have two tables: Category and Product, and Product links to Category with a foreign key Production.categoryId == Category.id. I would like my database server to take care of counting number of products within a category using a denormalized field Category.productCount - the triggers will update this count on any update/delete/insert, so I don't have to worry about it. Is there a way to synchronize database-side triggers with Doctrine2 entities somehow? I really don't want to recalculate those counters on PHP side, as we are going to run it on multiple servers.

2012-04-04 20:42
by KOHb


1

If I understand the question you want to be able to add a new product to a category, persist it then have Category.productCount update itself from the database? You can use

$entityManager->refresh($category);

To reload an entity from the database. I have not done it myself but I would expect that you could use the life cycle functionality to automate this.

But I do kind of wonder if it might not be better to just increment the counter locally without persisting it to the database. Let your trigger do the database operation but, within the request, update the count locally.

2012-04-05 14:03
by Cerad
This sounds like a good idea, thank you! The only problem I see is that Doctrine will send the denormalized fields to the database with every insert or update statement... is there a way to tell Doctrine that a field is "read-only" in this sense? Otherwise I can have a trigger on the server side that will ignore denormalized counts on inserts and updates... which would also work, I guess ; - KOHb 2012-04-07 23:36
I'm not sure about the read only. Might be better to use a change tracking policy such as deferred explicit http://docs.doctrine-project.org/projects/doctrine-orm/en/2.1/reference/change-tracking-policies.html and just avoid persisting the category object completely - Cerad 2012-04-08 11:23
Ads