简体   繁体   中英

Doctrine. Why i get persistentCollection and an empty array on ManyToMany?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM