Doctrine. Why i get persistentCollection and an em

2019-07-20 11:35发布

This is my Entity:

/**
* Productgeneral
* @ORM\Table(name="ProductGeneral", indexes={@ORM\Index(name="category_id", columns={"category_id"})})
* @ORM\Entity
*/
class Productgeneral {

    //some cols

    /**
     * @var integer
     *
     * @ORM\Column(name="product_id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $productId;

    /**
     * @var \Doctrine\Common\Collections\Collection
     *
     * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Productimg", inversedBy="product")
     * @ORM\JoinTable(name="producttoimg",
     *   joinColumns={
     *     @ORM\JoinColumn(name="product_id", referencedColumnName="product_id")
     *   },
     *   inverseJoinColumns={
     *     @ORM\JoinColumn(name="img_id", referencedColumnName="img_id")
     *   }
     * )
     */
    private $img;

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

    //getter & setters
}

/**
 * Productimg
 * @ORM\Table(name="ProductImg")
 * @ORM\Entity
 */
class Productimg {
    /**
     * @var integer
     *
     * @ORM\Column(name="img_id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $imgId;

    /**
     * @var \Doctrine\Common\Collections\Collection
     *
     * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Productgeneral", mappedBy="img")
     */
    private $product;

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

    //getters & setters
}

When I run:

*$this->getDoctrine()->getRepository('AppBundle:Productgeneral')->findAll();*

I get every column with its correct value but img; which returns a PersistentCollection instead of an array of all the images.

Am I doing something wrong? Or have I just misunderstand the behavior of the relationship?

1条回答
孤傲高冷的网名
2楼-- · 2019-07-20 12:01

The default Doctrine behaviour is to lazy fetch mapped entities so when you make a dump of your entity it appears to be null because the data have not been loaded.

If you call the getImg method then doctrine will query your database to load the related Productimg entities linked to your product.

Once an ArrayCollection is persisted and managed by the entity manager it becomes a PersistentCollection it behaves exactly has an ArrayCollection

查看更多
登录 后发表回答