我怎样才能使用 Symfony 原则访问相关实体?

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

我尝试查找与我的产品相关的所有文档:

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

}

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

foreach ($products as $key => $value) {
    dump($value->getDocuments()->getId());
}

但我收到错误消息:

Attempted to call an undefined method named "getId" of class "Doctrine\ORM\PersistentCollection".

getDocuments()returns多个product.documents的集合。因此,您还需要遍历这些文档,然后对单个项目使用 ->getId()

$value->getDocuments() return Doctrine 对象数组,或 PersistentCollection.

您的对象可能具有 getId() 功能,但 PersistentCollection 没有。

您可以遍历集合:

foreach ($products as $key => $value) {
    foreach ($value->getDocuments() as $document) {
        dump($document->getId());
    }
}