简体   繁体   中英

Doctrine2 repository, Many-to-Many associations and Twig templates: best practices

I have following question:

Imagine that we have an entity, eg Event .

In EventRepository class I've added some methods for querying some kind of Events.

In the EventController I've got a collection of Events. Last step - display all these Events in the template. Basically there is nothing difficult:

{% for event in events %}...{% endfor %}

But I have one additional condition : I need to display Users who goes to the each Event (eg 10 users for each). Event linked to the User with Many-to-Many association. Ok, I've added method to the EventRepository to find event participants. But I have no access to the EventRepository in Twig template... :(

I see three options:

  1. (quick and tricky) Get participants directly by the Entity: {% for event in events %}{% set participants = event.participants %}{% endfor %} . This works, but when we'll have participants count 1000+? Afaik event->getParticipants() will querying all 1000+ Users at once that will break my page.
  2. pass EventRepository instance into temlpate and query 10 users for each event, something like this: {% for event in events %}{% set participants = eventRepository.getEventParticipants(event.id, max) %}{% endfor %} . This looks more correct but looks like this breaks core MVC concepts - querying database within templates.
  3. Loop events in the controller and prepare Participants list for each. Look ugly (at least dooble loop for events and more code in controller), but more or less right (and what need to do when new conditions appears?).

Can you take any advise for this case? How I need to query NN relation and where in my code?

As long as your relationships are correctly set on your Event entity you should be able to lazy load the users when they're required. So for example when iterating over your events you should be able to call..

$event->getUsers();

Doctrine2 is really well suited for these exact types of operations (lazy loading the content when its required).

Make sure you have a valid relation between Events and Users and write a getter in your Events entity to pull out all users as either an array, or using Doctrine's ArrayCollection class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM