嘿伙计们,我又在寻求帮助了。
我的问题是两个相关的ORM实体没有被存储。
我运行以下单元测试,但它失败了:
public function testCategoryRelation()
{
$doctrine = $this->client->getContainer()->get('doctrine');
$itemRepo = $doctrine->getRepository("AppBundle:Item");
$item = $itemRepo->find(230045);
$this->assertTrue($item instanceof AcmeTestBundleEntityItem);
$categories = $item->getCategories();
$this->assertGreaterThan(0, $categories->count());
foreach ($categories as $category) {
$this->assertTrue($category instanceof AcmeTestBundleEntityCategory);
}
$count = $categories->count();
$categoryRepo = $doctrine->getRepository("AppBundle:Category");
$categories = $categoryRepo->findBy(array(), null, 2);
$this->assertEquals( 2, count($categories) );
foreach ($categories as $category) {
$this->assertTrue($category instanceof AcmeTestBundleEntityCategory);
$category->addItem($item);
$item->addCategory($category);
}
$this->assertGreaterThan($count, $item->getCategories()->count());
$em = $doctrine->getManager();
foreach ($categories as $category) {
$em->persist($category);
}
$em->persist($item);
$em->flush();
$em->clear($item);
$item = $itemRepo->find(230045);
$categories = $item->getRelatedItems();
$this->assertGreaterThan($count, $categories->count()); /* Here it fails */
}
我不知道为什么上次测试失败了。你能帮我找到我的错误吗?
我运行Symfony 2.1.4和Doctrine 2.3
我有两个ORM对象。
1. 项目
namespace AcmeTestBundleEntity;
use DoctrineORMMapping as ORM;
/**
* @ORMTable(name="item")
*/
class Item
{
/**
* @ORMManyToMany(targetEntity="Category", mappedBy="items")
*/
private $categories;
public function __construct()
{
$this->categories = new DoctrineCommonCollectionsArrayCollection();
}
/**
* @param AcmeTestBundleEntityCategory $category
*/
public function addCategory(AcmeTestBundleEntityCategory $category)
{
$this->categories[] = $category;
return $this;
}
/**
* @return DoctrineCommonCollectionsCollection
*/
public function getCategories()
{
return $this->categories;
}
}
2. 类别
namespace AcmeTestBundleEntity;
use DoctrineORMMapping as ORM;
/**
* @ORMTable(name="category")
* @ORMEntity(repositoryClass="AcmeTestBundleRepositoryCategoryRepository")
*/
class Category
{
/**
* @var DoctrineCommonCollectionsArrayCollection
*
* @ORMManyToMany(targetEntity="Item", inversedBy="categories")
* @ORMJoinTable(name="category_item",
* joinColumns={
* @ORMJoinColumn(name="cat_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* @ORMJoinColumn(name="item_id", referencedColumnName="id")
* }
* )
*/
private $items;
/**
* @param AcmeTestBundleEntityItem $item
* @return Category
*/
public function addItem(AcmeTestBundleEntityItem $item)
{
$this->items[] = $item;
return $this;
}
/**
* @return DoctrineCommonCollectionsCollection
*/
public function getItems()
{
return $this->items;
}
}
提前感谢您的帮助!
嗯,$categories = $item->getRelatedItems();
.也许写$categories = $item->getCategories();
更好?
另一个建议是将__construct方法添加到类别实体类并使用new ArrayCollection
初始化$items