【发布时间】:2014-01-13 16:30:06
【问题描述】:
当我尝试使用 symfony 表单持久化实体集合时遇到了一些问题。我关注了official documentation,但由于这个错误,我无法让它工作:
Entity of type ProductItem has identity through a
foreign entity Product, however this entity has no identity itself. You have to call
EntityManager#persist() on the related entity and make sure that an identifier was
generated before trying to persist ProductItem. In case of Post Insert ID
Generation (such as MySQL Auto-Increment or PostgreSQL SERIAL) this means you
have to call EntityManager#flush() between both persist operations.
我必须与 OneToMany 关系链接的实体:
产品
/**
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* @ORM\OneToMany(targetEntity="ProductItem", mappedBy="product",cascade={"persist"})
*/
protected $items;
产品项目
/**
* @ORM\Id()
* @ORM\ManyToOne(targetEntity="Product", inversedBy="items")
*/
protected $product;
/**
* @ORM\Id()
* @ORM\ManyToOne(targetEntity="Item")
*/
protected $item;
这是添加到表单中的方式:
->add('items','collection',array(
'label' => false,
'type' => new ProductItemType(),
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false))
这是控制器动作:
public function newAction()
{
$product= new Product();
$form = $this->createForm(new ProductType(), $product);
if($request->isMethod("POST"))
{
$form->handleRequest($request);
if($form->isValid())
{
$em = $this->getDoctrine()->getManager();
$em->persist($product);
$em->flush();
}
}
}
我肯定在控制器中做错了,因为正如错误消息所说,我必须在添加 $productItems 之前保留 $product,但我该怎么做呢?
我只在尝试持久化新实体时出现此错误,如果实体之前已持久化,我可以成功添加任意数量的项目
【问题讨论】:
-
可能你忘记在
ProductItem或Product上添加注解@ORM\Entity
标签: symfony doctrine-orm