How can I get access to related entities with Symfony doctrine?

Tags: , ,

I try to find all documents that are related to my product:

public function findDocumentsRelatedToProduct($id) {
        return $this->createQueryBuilder('products')
                        ->leftJoin('products.documents', 'pd')
                        ->where(" = :id")
                        ->setParameter(':id', $id)


$products = $this->em->getRepository('App\Entity\Products')->findDocumentsRelatedToProduct($id);

foreach ($products as $key => $value) {

But I get the error message:

Attempted to call an undefined method named “getId” of class “DoctrineORMPersistentCollection”.


The $value->getDocuments() return an array of Doctrine objects, or a PersistentCollection.

Your object may have a getId() function, but the PersistentCollection doesn’t.

You can loop over the Collection :

foreach ($products as $key => $value) {
    foreach ($value->getDocuments() as $document) {

Source: stackoverflow