我有一个表格,允许我保存记录或复制它.表单将记录保存为$view实体,该实体恰好具有多个关联实体,例如$viewVersion由具有嵌套实体的formType中的表单构建器管理(这可能是无关紧要的).
如果我进行更改并将表单提交为"复制",则代码将$view使用我的实体上的函数克隆对象,该函数将取消设置$view->id和其他关联.这迫使Doctrine在将记录保存到数据库时创建新记录.这非常有效.欢呼!
但是,对记录所做的更改也会持久保存到克隆的原始实体(并因此保存到数据库中).因此它将这些更改保存到两个数据库记录中.我碰巧喜欢这个功能,但我需要理解为什么它正在这样做,所以它不会破坏.以下是摘要中相关的代码:
// File: CmsBundle/Controller/AdminEditController.php
// Get the Entity Manager
$em = $this->getDoctrine()->getManager();
// Get the View based on the requested ID
// Is there some magic that happens here to make the entity manager track this $view entity?
$view = $em->getRepository("GutensiteCmsBundle:View\View")->find($request->query->get('id'));
// Various bits of code to do whatever I want before a save
// ...
if ($request->isMethod( 'POST' )) {
$form->handleRequest($request);
if( $form->isValid() ) {
// Duplicate the view …Run Code Online (Sandbox Code Playgroud) 我遇到了以下问题.应用程序需要能够克隆Season具有所有相关实体的实体.我在这个伟大的问题上受到启发- 一切都按照它应有的方式运作,但ManyToMany在路上存在关系问题.
请查看附图,其中显示了数据库图表的一小部分,显示了我遇到问题的部分.
我想达到的状态是有一个克隆一个的Price绑定到实体的现有 Offer实体.说清楚 - 我不能也绝不能克隆Offer实体,实体的新克隆实例Price必须绑定到主Price实体实例绑定的同一个实例.
offer_price克隆之前表的示例内容 offer_id | price_id
----------+----------
47 | 77
Run Code Online (Sandbox Code Playgroud)
offer_price克隆后表的预期内容 offer_id | price_id
----------+----------
47 | 77
47 | 79
Run Code Online (Sandbox Code Playgroud)
...假设PriceID 77是主记录Price,ID 79是绑定到同一Offer记录的新克隆实例.
/**
* @Entity
*/
class Price
{
...
/**
* @var \Doctrine\Common\Collections\Collection of Offer
* @ManyToMany(targetEntity="Offer", mappedBy="prices", cascade={"persist"})
*
* @get …Run Code Online (Sandbox Code Playgroud) 我有一个与媒体实体有一对多关系的Product实体
/**
* @ORM\OneToMany(targetEntity="Norwalk\StoreBundle\Entity\ProductHasMedia", mappedBy="product", cascade={"persist"}, orphanRemoval=true )
*/
protected $imagenes;
Run Code Online (Sandbox Code Playgroud)
与Package实体的一对一关系
/**
* @ORM\OneToOne(targetEntity="Package", cascade={"persist"})
* @ORM\JoinColumn(name="package", referencedColumnName="id")
*/
protected $package;
Run Code Online (Sandbox Code Playgroud)
我能够使用此功能克隆Product实体
public function __clone() {
if ($this->id) {
$this->package = clone $this->package;
}
// Get current collection
$imagenes = $this->getImagenes();
$this->imagenes = new ArrayCollection();
if(count($imagenes) > 0){
foreach ($imagenes as $imagen) {
$cloneImagen = clone $imagen;
$this->imagenes->add($cloneImagen);
$cloneImagen->setProduct($this);
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题是,新实体已将与原始实体相同的图像关联起来.这意味着如果我删除一个实体中的图像,它也会被删除.请参阅下表,其中原始产品(ID为5)与克隆产品具有相同的介质(ID为7)

我需要的是,这些克隆的图像有一个新的ID,而II需要它们与原始实体无关,例如,当我从克隆实体中删除一些图像时,它不会影响到原始实体.
有任何想法吗?:)
提前致谢