Symfony2 fetch data from entity with OneToMany relation
I have two entities: Ad
and AdPhoto
. They have relation: OneToMany(Many AdPhoto to one Ad).
After persist, I tried to get AdPhoto
from Ad
by method Ad::getPhoto()
, but I get PersistentCollection
class and I dont know what do with it.
Help me to understand how I can get all related AdPhoto to Ad.
Entity Ad:
namespace AdBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Ad
*
* @ORM\Table(name="Ad")
* @ORM\Entity
*/
class Ad
{
...
/**
* @ORM\OneToMany(targetEntity="AdBundle\Entity\AdPhoto", mappedBy="id")
*/
private $photo;
...
}
Entity AdPhoto:
namespace AdBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Validator\Constraints as Assert;
/**
* AdPhoto
*
* @ORM\Table(name="AdPhoto")
* @ORM\Entity
*/
class AdPhoto
{
...
/**
* @ORM\ManyToOne(targetEntity="AdBundle\Entity\Ad", inversedBy="photo")
* @ORM\JoinColumn(name="ad", referencedColumnName="id")
*/
private $ad;
...
}
In controller:
$ad = $this->getDoctrine()->getRepository('AdBundle:Ad')
->findOneBy(array(
'id' => $id
));
var_dump($ad->getPhoto());
return $this->render('AdBundle:Default:view.html.twig', array(
'ad' => $ad
));
You can loop through array collection in twig like through regular array. If you want to use it as array in php code you can use
$photos = $ad->getPhotos()->toArray();
And since add can have many photos it would be better to use $photos instead $photo.