I am writing a small, forum-like application (in Symfony2) and I am running into the following problem:
I have two Entities:
class ForumThread {
public $fourmThreadId;
public $title;
public $posts; // aggregation field -> ArrayCollection of ForumPost (can't be empty)
}
class ForumPost {
public $content;
public $timeCreated;
public $thread; // aggregation field -> ForumThread (can't be null)
}
I now want to get all forum threads, including only the newest post of each thread. I want to use it for the forum overview:
-------------------------------------
| Thread | Last Post |
-------------------------------------
| Name of Thread #1 | ### |
| Name of Thread #2 | ### |
| ... | ... |
-------------------------------------
I want to fetch the complete ForumPost entity, not just a single field (like the timestamp).
Also it should be performant: ideally in 1-2 queries (I have found something in raw SQL using INNER JOINs, but I want in DQL or ideally using the QueryBuilder – and my translation tries from SQL to DQL did not succeed).
Ok, I found a solution, which works but is not be the best way:
Notice the subquery in the
WHEREclause. This works, but has a flaw: it joins using the timestamp field (to prevent the additional nested subquery – which did always produce parsing errors in DQL), which may not be unique, even for the given thread.