1

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
        ));
1
  • Edit the question and put the code you tried Commented Dec 3, 2015 at 20:38

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, I should try it in the morning. Rename $photo to $photos it`s a good proposition. Thanks!
0

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];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.