0

There are other questions on this but they don't cover my use case, I think.

I have a User, a User has Projects. A Project can be published or not.

Within Twig (in several places, in several templates) I wish to display the number of published Projects a User has.

This information is not stored, directly, within the Entity of the User. I could write a function to do this within the User Entity, but that would involve iterating over the Projects and checking each one's published status. This seems slow.

The other way is to write a query within the User Repo and get a count of all the published Projects. But that would mean ensuring that query from the Repo is executed in each Controller and then assigned to each Twig view. This feels suboptimal also as I need to count in lots of places and so would be repeating this Repo query in lots of places. Possibly in every Controller.

How can I therefore get this count from within Twig, from the User Entity or from the Repo?

Jake N
  • 10,535
  • 11
  • 66
  • 112
  • Do your query from a twig extension. – Cerad Jan 29 '15 at 00:14
  • You could use Doctrine postLoad event (see more here: http://doctrine-orm.readthedocs.org/en/latest/reference/events.html#postload) to set any additional properties to your entity after it's loaded from its repository. For example you could create special properties and appropriate set nd get methods to get projects number for current user. – Alex Jan 29 '15 at 05:58
  • @Alex doesn't that suffer from efficiency issues? This is not a query, but instead is looping over all the Projects in order to check their published attribute, to then build a new collection of Projects. – Jake N Jan 29 '15 at 12:56
  • @Cerad Presumably like this? http://stackoverflow.com/questions/8450465/fetching-data-through-a-custom-repository-in-a-twig-extension – Jake N Jan 29 '15 at 12:58
  • @Cerad I went for this approach - works really well! Thanks for the hint. – Jake N Jan 29 '15 at 14:25

1 Answers1

0

I would simply have a count in the ProjectEntity where published = true and id = userId, and pass the info to the twig template

mezod
  • 2,313
  • 3
  • 21
  • 31
  • But that involves iterating over the Projects to get count, which is slow. – Jake N Jan 28 '15 at 23:10
  • it is a very simple and efficient sql query... and probably there's no more efficient way that won't be a headache – mezod Jan 28 '15 at 23:24
  • What if there a million Projects? Each needs looping over. Via a query its much faster when the `published` attribute is indexed. – Jake N Jan 28 '15 at 23:25
  • either that or you have a counter in the user entity, but there's no way around it really – mezod Jan 28 '15 at 23:28