0

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() the User with Comment table on the user ID. I think I want a LEFT 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 the text of the most recent comment, but I could probably get the MAX(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.

cheryllium
  • 430
  • 4
  • 15
  • Your first 2 bullet items show that you understand SQL. "Confused on how to translate that to query builder syntax" says that the framework is in the way. – Rick James Apr 27 '21 at 23:45
  • Good point; I will remove the 'mysql' tag from my question. Thanks! – cheryllium Apr 28 '21 at 00:23
  • Have you checked whether you can apply [Criteria](https://www.doctrine-project.org/projects/doctrine-orm/en/2.8/reference/working-with-associations.html#filtering-collections) collection filtering for it? Seems like a good approach to me. – LBA Apr 28 '21 at 13:19

0 Answers0