【发布时间】:2014-01-04 23:53:38
【问题描述】:
过了一会儿,我又回到了教义上。我对教义和 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() 是否应该返回该类别的项目?还是我错觉它应该起作用?请提出建议。
虽然数据库中有数据,但现在返回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
谢谢
【问题讨论】:
-
它应该可以工作。问题是什么?有没有错误?打印
$category->getItems()的结果是什么? -
感谢您回来 Shad。它什么也不返回。虽然,数据库中有数据。
-
您是否尝试将
public function __construct() { $this->items = new ArrayCollection(); }放入类别实体中? -
它已经在那里了。抱歉,我在此处粘贴时省略了该部分。
-
我已经在本地测试过它并且它有效。应该返回
Doctrine\ORM\PersistentCollection对象
标签: symfony doctrine-orm