Doctrine,不能迭代集合的项目

时间:2015-08-28 06:24:45

标签: php zend-framework2 doctrine one-to-many

我在阅读 n:m 关系时遇到了麻烦。 我有一个Collection-Table,该集合每个Collection收集几个项目。 为了解决这个问题,我在Doctrine中有2个实体,如下所示:

我的收藏

<?php

namespace my\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * myCollection
 * @package my\Entity
 *
 * @ORM\Entity
 * @ORM\Table(name="collections")
 */
class Collection
{
    /**
     * @var int
     *
     * @ORM\Id
     * @ORM\Column(name="id", type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var
     * @ORM\OneToMany(targetEntity="Item", mappedBy="id", cascade="all")
     */
    private $items;

    public function __construct(){
        $this->items = new ArrayCollection();
    }

    public function add(Item $oItem){
        $this->items->add($oItem);
        $oItem->setCollection($this);
    }

    /**
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param int $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    public function getItems(){
        return $this->items;
    }

}

和项目

<?php

namespace my\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * myItem
 * @package my\Entity
 *
 * @ORM\Entity
 * @ORM\Table(name="items")
 */
class Item
{
    /**
     * @var int
     *
     * @ORM\Id
     * @ORM\Column(name="id", type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var
     * @ORM\ManyToOne(targetEntity="Collection", inversedBy="items")
     * @ORM\JoinColumn(name="cid", referencedColumnName="id")
     */
    protected $collection;

    public function setCollection(Collection $col = null){
        $this->collection = $col;
    }

    public function getCollection(){
        return $this->collection;
    }

    /**
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }
}

创建新项目工作正常。通过fk / pk键获取与集合相关的DB中的项目。

public function testCreate(){
    $i1 = new Item();
    $i2 = new Item();
    $c = new Collection();
    $c->add($i1);
    $c->add($i2);

    $em = $this->getEntityManager();
    $em->persist($c);
    $em->flush();
}

但是当我这样读的时候:

public function testRead(){
    $result = $this->getEntityManager()->getRepository('my\Entity\Collection')->findOneById(1);
    $this->sDesktop .= '<br>found '.count($result).' items in collection';
    $items = $result->getItems();
    foreach($items as $item){
        //$this->sDesktop .= '<br>' . $item->getId();
    }
}

收藏工作做得很好,我可以访问它。但是对其项目的迭代正在崩溃。

错误是:

  

注意:第1768行/var/www/html/myproj/vendor/doctrine/orm/lib/Doctrine/ORM/Persisters/Entity/BasicEntityPersister.php中的未定义索引:id

我找不到解决方案。 有谁能告诉我发生了什么?

1 个答案:

答案 0 :(得分:0)

检查Collection模型:mappedBy应设置为'collection'

/**
 * @var
 * @ORM\OneToMany(targetEntity="Item", mappedBy="collection", cascade="all")
 */
private $items;
相关问题