In my entity documents
I have a field called linkedDocuments
:
class Documents {
/**
* @ORM\ManyToMany(targetEntity="App\Entity\Documents")
* @ORM\JoinTable(name="documents_documents",
* joinColumns={@JoinColumn(name="link_origin", referencedColumnName="id")},
* inverseJoinColumns={@JoinColumn(name="link_destination", referencedColumnName="id")}
* )
* @Groups("documents")
*/
private $linkedDocuments;
public function __construct() {
$this->linkedDocuments = new ArrayCollection();
}
In my controller I create an object:
$table = $this->em->getRepository(Documents::class)->findAll();
This is the output:
array:1 [▼
0 => Documents^ {#6414 ▼
-id: 1
-linkedDocuments: PersistentCollection^ {#5724 ▼
-snapshot: []
-owner: Documents^ {#6414}
-association: array:19 [ …19]
-em: EntityManager^ {#2786 …11}
-backRefFieldName: null
-typeClass: ClassMetadata {#2613 …}
-isDirty: false
#collection: ArrayCollection^ {#2820 ▼
-elements: []
}
#initialized: true
}
}
]
My Array Collection is empty. But I expect it to have two elements, because I see them in my mySQL database. Like this:
-elements: array:2 [▼
0 => linkedDocuments^ {#1204 ▶}
1 => linkedDocuments ▶}
]
I found a solution. Instead of this:
$table = $this->em->getRepository(Documents::class)->findAll();
I had to write this:
$table = $this->em->getRepository(Documents::class)->linkedDocuments($id);
And in my DocumentsRepository I added the function:
public function linkedDocuments($id)
{
return $this->createQueryBuilder('d')
->leftJoin('d.linkedDocuments', 'dd')
->where('d.id = :id')
->setParameter(':id', $id)
->getQuery()
->execute();
}