2

Entity/User.php:

    // ...
    use Doctrine\Common\Collections\ArrayCollection;
    // ...

    /**
     * @var ArrayCollection
     *
     * @ORM\OneToMany(targetEntity="Picture", mappedBy="user")
     * @ORM\OrderBy({"file" = "ASC"})
     **/
    private $pictures;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->pictures = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Add picture
     *
     * @param \MyBundle\Entity\Picture $picture
     *
     * @return User
     */
    public function addPicture(\MyBundle\Entity\Picture $picture)
    {
        $this->pictures[] = $picture;

        return $this;
    }

    /**
     * Remove picture
     *
     * @param \MyBundle\Entity\Picture $picture
     */
    public function removePicture(\MyBundle\Entity\Picture $picture)
    {
        $this->pictures->removeElement($picture);
    }

    /**
     * Get pictures
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getPictures()
    {
        return $this->pictures;
    }

   // ...

Entity/Picture.php

// ...

/**
 * @var ArrayCollection
 *
 * @ORM\ManyToOne(targetEntity="User", inversedBy="pictures")
 * @ORM\JoinColumn(name="user", referencedColumnName="id")
 */
private $user;

/**
 * Set user
 *
 * @param \MyBundle\Entity\User $user
 *
 * @return Picture
 */
public function setUser(\MyBundle\Entity\User $user = null)
{
    $this->user = $user;

    return $this;
}

/**
 * Get user
 *
 * @return \MyBundle\Entity\User
 */
public function getUser()
{
    return $this->user;
}

// ...

Controller/PictureController.php:

// ...

public function indexAction(Request $request)
    {
        return array(
            'pictures' => $this->getUser()->getPictures(),
        );
    }

// ...

This is what Symfony's profiler outputs when I dump the result of ->getPictures():

PersistentCollection {#292 ▼
  -snapshot: []
  -owner: User {#270 ▶}
  -association: array:16 [ …16]
  -em: EntityManager {#53 …11}
  -backRefFieldName: "user"
  -typeClass: ClassMetadata {#272 …}
  -isDirty: false
  #collection: ArrayCollection {#293 ▶}
  #initialized: false
}

Somehow the collection is not initialized and it has no items, although there are some in the database... What point am I missing here?

cnmicha
  • 164
  • 1
  • 3
  • 12

1 Answers1

0

Add this to your doctrine annotation to make it lazy load the related entity;

@ORM\OneToMany(targetEntity="Picture", mappedBy="user",fetch="EAGER")

Acute X
  • 92
  • 1
  • 4