I have the following tables (and entities in symfony2 / doctrine2):
+------------------+ +--------------------+
| forum_sections | | forum_categories |
+------------------+ +--------------------+
| id ├--------| | id |
| title | |---------| section |
| position | | position |
| created_at | | title |
+------------------+ | description |
+--------------------+
I want to archive the following html page (without the bullets ofcource):
- this is a title (from forum_sections->title)
- forum 1 (from forum_categories->title)
- forum 2 (from forum_categories->title)
- this is another title (from forum_sections->title)
- forum 3 (from forum_categories->title)
I did some research on how to do this. So far I tried the following in my twig layout:
{% for section in sections %}
<h1>title</h1>
{% for category in categories %}
bla bla
{% endfor %}
{% endfor %}
Is this even possible with a 'findAll' query in Doctrine2? I tried some combinations, but they seem to get all the boards ignoring the sections.
I think the problem is in your entities, the way you define the relationship between entitites. You need to use bidirectional mapping http://doctrine-orm.readthedocs.org/en/latest/reference/association-mapping.html#one-to-many-bidirectional
I updated your entities to fit your needs.
ForumSection
entityForumSection
entityinversedBy
annotation toForumCategory
entity to complete te relationshipThe entities;
ForumSection.php
ForumCategory.php
The controller;
The template;
Now you have access to categories related to each forum_section row in your database.
And this is the output after I run the code
hello
world
I have to mention that Doctrine uses lazy loading by default.Doctrine will perform extra queries to find categories related to forums. If you have
n
forums you will haven + 1
queries. In my case I used 2 forum sections and here are the queries.This one finds all the forum_sections;
SELECT t0.id AS id1, t0.title AS title2, t0.position AS position3, t0.created_at AS created_at4 FROM forum_sections t0
Then for each forum, doctrine executes another query to find categories with different parameters. This queries don't get executed untill you call 'forum.getCategories()` method.
SELECT t0.id AS id1, t0.position AS position2, t0.title AS title3, t0.description AS description4, t0.section AS section5 FROM forum_categories t0 WHERE t0.section = ? [Parameters: 1,2]
Check out fetch-join concept to learn more about lazy loading and alternatives. http://blog.bemycto.com/good-practices/2015-05-31/understanding-doctrine-orm-lazy-load-fetch-join/