[英]Removing OneToMany elements, Doctrine2
I've got this model; 我有这个模型。 Itinerary, Venue, ItineraryVenue.
路线,地点,路线地点。
I needed many to many relation between itineraries and venues but also I wanted to store some specific data about the relation (say notes, own photo, etc.), so I decided to introduce a new entity named ItineraryVenue. 我需要在路线和地点之间建立多对多的联系,但我也想存储一些有关该联系的特定数据(例如注释,自己的照片等),因此我决定引入一个名为ItineraryVenue的新实体。
So Itinerary has collection of ItineraryVenues which in turn, refer to Venues. 因此,行程中包含了IteneraryVenues集合,后者又称为Venues。
My problem is that I can't remove ItineraryVenue from a Itinerary object. 我的问题是我无法从Itinerary对象中删除ItineraryVenue。
$itinerary->itineraryVenues->removeElement($itineraryVenue);
$em->flush();
removes element from the php collection, but doesn't remove this $itineraryVenue from database. 从php集合中删除元素,但不从数据库中删除此$ itineraryVenue。
I've managed to force Doctrine2 to remove $itineraryVenue, but only when I annotate the Itinerary::$itineraryVenues
with orphanRemoval=true
. 我设法强迫Doctrine2删除$
orphanRemoval=true
,但仅当我使用orphanRemoval=true
注释Itinerary::$itineraryVenues
orphanRemoval=true
。
Since orphan removal treats Venue as a private property it also removes Venue entity, I don't want that. 由于孤儿搬迁会将Venue视为私有财产,因此也会删除Venue实体,因此我不希望这样做。
Is there an relation configuration option or is removing "by hand" the olny way to make it work as I want? 有关系配置选项还是正在手动删除“手工”方式以使其按我的意愿工作?
Hard to believe it, it's a common relation pattern. 很难相信,这是一种常见的关系模式。
Entities definitions: 实体定义:
class Itinerary
{
/**
* @ORM\OneToMany(targetEntity="ItineraryVenue", mappedBy="itinerary", cascade={"persist", "remove"})
*/
private $itineraryVenues;
function __construct()
{
$this->itineraryVenues = new ArrayCollection();
}
}
class ItineraryVenue
{
/**
* @ORM\ManyToOne(targetEntity="Itinerary", inversedBy="itineraryVenues")
*/
private $itinerary;
/**
* @ORM\ManyToOne(targetEntity="Venue")
*/
private $venue;
function __construct()
{
}
}
class Venue
{
}
You are doing things right: orphanRemoval - is what you need. 您做对了:orphanRemoval-您需要的是。 So, you should override default Itinerary::removeItineraryVenue like
因此,您应该像这样重写默认Itinerary :: removeItineraryVenue
public function removeItineraryVenue(\AppBundle\Entity\ItineraryVenue $itineraryVenue)
{
$itineraryVenue->setItinerary(null);
$this->itineraryVenues->removeElement($itineraryVenue);
}
The full working example is here https://github.com/kaduev13/removing-onetomany-elements-doctrine2 . 完整的工作示例在这里https://github.com/kaduev13/removing-onetomany-elements-doctrine2 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.