【问题标题】:Doctrine. Why i get persistentCollection and an empty array on ManyToMany?教义。为什么我在 ManyToMany 上得到 persistentCollection 和一个空数组?
【发布时间】:2017-05-31 22:14:48
【问题描述】:

这是我的实体:

/**
* 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
}

当我跑步时:

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

我得到了每一列的正确值,但 img;它返回一个 PersistentCollection 而不是所有图像的数组。

我做错了吗?还是我只是误解了这段关系的行为?

【问题讨论】:

  • 你创建了setter和getter吗?您需要一个 setImage( AppBundle\Entity\Productimg $img ) 将图像添加到 ArrayCollection。
  • 您是否尝试迭代 PersistentCollection?你检查producttoimg表中是否有数据?
  • * 是的,我有以下 getter 和 setter:添加 img、删除 img、获取 img。 * 所有表格都填充了正确的数据 * PersistentCollection 的#collection 为空。我是通过Twig的dump函数看到的

标签: php symfony doctrine-orm orm doctrine


【解决方案1】:

默认的 Doctrine 行为是延迟获取映射的实体,因此当您转储实体时,它似乎为 null,因为尚未加载数据。

如果您调用 getImg 方法,则学说将查询您的数据库以加载链接到您的产品的相关 Productimg 实体。

一旦 ArrayCollection 被实体管理器持久化和管理,它就变成了 PersistentCollection,它的行为完全具有 ArrayCollection

【讨论】:

  • 当我调用 getImg() 时没有任何变化。仍然使用空的#collection 获取 PersistenCollection。方法:pastebin.com/kH0nuSzA
猜你喜欢
  • 2016-11-19
  • 1970-01-01
  • 2014-01-22
  • 2014-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-09
相关资源
最近更新 更多