trauma
trauma

Reputation: 322

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
        ));

Upvotes: 1

Views: 2625

Answers (2)

Allart
Allart

Reputation: 928

Ivan Toncev it's answer is great, but there is an extra thing you might want to know about to make things more understandable.

PersistentCollection does have the value's you need. You just don't see it when you log them. Idk why.

You could try out the following things to check if there is actually data existing:

$ad->getPhotos()->count(); // Counts the amount of items (rows).

count($ad->getPhotos()); // Same as above.
// Loop trough all photo's.
for ($i = 0; $i < count($ad->getPhotos()); $i++) {

    // A single photo!
    $photo = $ad->getPhotos()[$i];
}

Upvotes: 0

Ivan Toncev
Ivan Toncev

Reputation: 532

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.

Upvotes: 1

Related Questions