user2626210
user2626210

Reputation: 125

DQL: Join table and return all results when at least one joined column fulfills a condition

I have two entities in Doctrine: oneToMany between Post and Comments. Comments are owned by a User. I want to retrieve all posts and comments for which at least one comment is owned by a certain user. What would be the proper way of achieving that with Doctrine's Query Builder?

$em->createQueryBuilder('p')
  ->innerJoin('p.comments','c')
  ->having(AT LEAST ON c.user = :user)
  ->where(p.id = :idPost)

Could you help me folks ?

Upvotes: 0

Views: 106

Answers (1)

scoolnico
scoolnico

Reputation: 3135

Here is a solution:

$query = $em->createQueryBuilder('p')
  ->leftJoin('p.comments','c')
  ->where('c.user = :user')
  ->andwhere('p.id = :idPost')
  ->setParameter('idPost', '1')
  ->setParameter('user', 'Toto')
;

return $query->getQuery()->getResult();

Upvotes: 1

Related Questions