0

I have two tables clients and contacts and contacts has client_id as foreign key

$client = $this->getDoctrine()->getRepository('MyBundle:Client')->findAll();

This gives the data from table clients but I need data from contacts as well which has the related client id

Note: I am using embed forms, CollectionType, ArrayCollection

how do I get all clients with respective contacts in one query in symfony 3

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user75472
  • 1,277
  • 4
  • 28
  • 53

1 Answers1

0

you can create a join query like this inside a function into your repository:

public function getAllClientWithContacts()
{
    $qb = $this->createQueryBuilder();
    $qb
        ->select('c')
        ->from('MyBundle\Entity\Client', 'c')
        ->leftJoin('MyBundle\Entity\Contact');

    return $qb->getQuery()->getResult();
}
Alessandro Minoccheri
  • 35,521
  • 22
  • 122
  • 171
  • Thanks @alessandro. However this didn't work for me I used the following and this worked but I still need to figure out if this is the correct way in symfony 3 public function getAllClientWithContacts() { $query = $this->getEntityManager() ->createQuery( 'SELECT c,cs FROM JimmyBundle:Client c JOIN c.contacts cs ORDER BY c.id ASC' ); try { return $query->getResult(); } catch (\Doctrine\ORM\NoResultException $e) { return null; } } – user75472 May 31 '17 at 12:09
  • Yes is another way and this can works, I hope to have helped you to solve your problem! – Alessandro Minoccheri May 31 '17 at 12:12