Details
Description
When merging a DETACHED entity into the repository with a ManyToMany association, the entries in the join table are deleted on the next flush.
Many Movies have many Artists:
class Movie {
/** @Id @Column(type="integer") @GeneratedValue(strategy="IDENTITY") */
public $id;
/** @Column(length=50, type="string") */
public $title;
/**
* @ManyToMany(targetEntity="Artist")
*/
public $artists;
public function __construct() {
$this->artists = new ArrayCollection();
}
}
class Artist {
/** @Id @Column(type="integer") @GeneratedValue(strategy="IDENTITY") */
public $id;
/** @Column(length=50, type="string") */
public $name;
/** @ManyToMany(targetEntity="Movie", mappedBy="artists") */
public $movies;
public function __construct() {
$this->movies = new ArrayCollection();
}
}
Assume that the database contains:
Movie: id=1, title="Movie 1"
Artist: id=1, name="Artist 1"
and that there is a entry (1, 1) in movie_artist so that there is a many-many relationship between Movie 1 and Artist 1.
I then run the following code to merge the existing associations into the entity manager:
$m1 = new \vo\Movie(); $m1->id = 1; $m1->title = "Movie 1"; $a1 = new \vo\Artist(); $a1->id = 1; $a1->name = "Artist 1"; $m1->artists->add($a1); $a1->movies->add($m1); $m1 = $em->merge($m1); $m1->artists->set(0, $em->merge($a1)); $a1->movies->set(0, $em->merge($m1));
At this point $m1 should contains merged entities reflecting the same as what is in the database.
If I now run:
$em->flush()
the association is deleted from movie_artist and the SQL log shows DELETE FROM Movie_Artist WHERE Movie_id = '1' as having been run.
Debugging $m1 both before and after the flush shows the expected values, and $em->getUnitOfWork()->computeChangeSets() is empty before the flush.
Can you explain why you merge $m1 twice?