Let's say I have entities User
and Comment
in a one-to-many relationship. Assume the relationship is set up correctly in the models and is called comments
on the User
model. Let's say Comment
has a field text
that is the text written in the comment.
Each Comment
belongs to one User
, but each User
may have any number of comments (including no comments at all.)
I'm using Doctrine-ORM 2.7. I need to select User
data and only the text
of their most recent comment if it exists. I'm really struggling to piece together how to do this. My thoughts so far:
- The query should
leftJoin()
theUser
withComment
table on the user ID. I think I want aLEFT JOIN
since that way users without any comments are still selected. - The Comments part needs to be a nested query that does something like
ORDER BY id DESC LIMIT 1
on the comments that have that user ID, so that only the most recent one is selected. - I don't think I can use
groupBy()
since I need to select thetext
of the most recent comment, but I could probably get theMAX(comment.id)
through here and that might come in handy?
My progress on an attempt so far:
$qb = $em->getRepository(User::class)
->createQueryBuilder('u')
->select('u.id, u.username') // ...etc. user data
->addSelect('c.text') // comment text
->leftJoin('u.comments', 'c', 'WITH', ....) // Place nested subquery here somehow?
->getQuery()
->getArrayResult();
I feel like the nested query has to be something like this:
$qb = $em->getRepository(Comment::class)
->createQueryBuilder('c')
->select('c.id')
->where('c.user', ':user')
->orderBy('id', 'desc')
->getQuery()
->getScalarResult();
This is a made-up example; in the real application, optimization is a concern so I'd like to minimize the number of nested queries executed. This answer seems to have a good raw SQL approach, but I'm getting confused on how to translate that to query builder syntax. Any help would be appreciated.