Symfony 2 Doctrine 2一对多关系不返回数据

时间:2014-01-04 23:53:38

标签: symfony doctrine-orm

过了一会儿,我回到了学说。我对学说和symfony有一些问题,我根本无法弄明白,为什么会这样。帮助会很好。

我有两个实体: 1.分类:

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


/**
 * @ORM\OneToMany(targetEntity="Items", mappedBy="category")
 */
private $items;


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



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

/**
 *
 * @param Items $items
 * @return Category
 */
public function addItem(Items $item)
{
    $this->items[] = $item;

    return $this;
}

/**
 *
 * @param Items $item
 */
public function removeItem(Items $item)
{
    $this->items->removeElement($item);
}

/**
 * @return Items
 */
public function getItems()
{
    return $this->items;
}

第二是:项目

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

 /**
 * @var integer
 *
 * @ORM\ManyToOne(targetEntity="Category", inversedBy="items")
 * @ORM\JoinColumn(name="category_id", referencedColumnName="id")
 */
 private $category;


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

 /**
 * Set category
 *
 * @param Category $category
 * @return Items
 */
 public function setCategory(Category $category = null)
 {
    $this->category = $category;

    return $this;
 }

 /**
  * Get category
  *
  * @return Category 
  */
 public function getCategory()
 {
    return $this->category;
 }

现在在Controller中,我只是想通过类别检索项目:

    $categories = $em->getRepository('Category')->findAll();  
    //just example 
    foreach ($categories as $category) {
        print_r($category->getItems());
    }

$ category-> getItems()应该返回该类别的Items吗?或者我觉得它应该有效?请建议。

虽然数据库中有数据,但它现在返回null但不是错误。

表结构是:

  CREATE TABLE `category` (

 `id` int(11) NOT NULL AUTO_INCREMENT,

  PRIMARY KEY (`id`)

 ) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8

 CREATE TABLE `items` (

 `id` int(11) NOT NULL AUTO_INCREMENT,

 `category_id` int(11) DEFAULT NULL,

  PRIMARY KEY (`id`),

  KEY `fk_category` (`category_id`),

 CONSTRAINT `fk_category` FOREIGN KEY (`category_id`) REFERENCES `Category` (`id`)

 ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8

由于

3 个答案:

答案 0 :(得分:1)

2年后..我也希望使用最新的Symfony和Doctrine以及$ category-> getItems()

在我的情况下,我必须做的是:

控制器:

$items = $em->getRepository('AppBundle:Items')->findByCategory($category);

出于某种原因 - > getItems()为空。

答案 1 :(得分:0)

您需要在添加项目时设置项目的类别,否则它将作为NULL而不是类别ID保存在数据库中。

/**
 *
 * @param Items $items
 * @return Category
 */
public function addItem(Items $item)
{
    $item->setCategory($this);
    $this->items[] = $item;

    return $this;
}

答案 2 :(得分:0)

尝试:

\Doctrine\Common\Util\Debug::dump($category->getItems()); 

而不是

print_r($category->getItems());

当我因某种原因尝试dump()函数而没有转储结果时,我面临同样的问题