1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
|
<?php
declare(strict_types=1);
namespace Doctrine\Tests\ORM\Functional\Ticket;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\GeneratedValue;
use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping\ManyToOne;
use Doctrine\ORM\Mapping\OneToMany;
use Doctrine\Tests\OrmFunctionalTestCase;
class DDC735Test extends OrmFunctionalTestCase
{
protected function setUp(): void
{
parent::setUp();
$this->createSchemaForModels(DDC735Product::class, DDC735Review::class);
}
public function testRemoveElementAppliesOrphanRemoval(): void
{
// Create a product and its first review
$product = new DDC735Product();
$review = new DDC735Review($product);
// Persist and flush
$this->_em->persist($product);
$this->_em->flush();
// Now you see it
self::assertCount(1, $product->getReviews());
// Remove the review
$reviewId = $review->getId();
$product->removeReview($review);
$this->_em->flush();
// Now you don't
self::assertCount(0, $product->getReviews(), 'count($reviews) should be 0 after removing its only Review');
// Refresh
$this->_em->refresh($product);
// It should still be 0
self::assertCount(0, $product->getReviews(), 'count($reviews) should still be 0 after the refresh');
// Review should also not be available anymore
self::assertNull($this->_em->find(DDC735Review::class, $reviewId));
}
}
/** @Entity */
class DDC735Product
{
/**
* @var int
* @Id
* @Column(type="integer")
* @GeneratedValue
*/
protected $id;
/**
* @psalm-var Collection<int, DDC735Review>
* @OneToMany(
* targetEntity="DDC735Review",
* mappedBy="product",
* cascade={"persist"},
* orphanRemoval=true
* )
*/
protected $reviews;
public function __construct()
{
$this->reviews = new ArrayCollection();
}
/** @psalm-return Collection<int, DDC735Review> */
public function getReviews(): Collection
{
return $this->reviews;
}
public function addReview(DDC735Review $review): void
{
$this->reviews->add($review);
}
public function removeReview(DDC735Review $review): void
{
$this->reviews->removeElement($review);
}
}
/** @Entity */
class DDC735Review
{
/**
* @var int
* @Id
* @Column(type="integer")
* @GeneratedValue
*/
protected $id;
/**
* @var DDC735Product
* @ManyToOne(targetEntity="DDC735Product", inversedBy="reviews")
*/
protected $product;
public function __construct(DDC735Product $product)
{
$this->product = $product;
$product->addReview($this);
}
public function getId(): int
{
return $this->id;
}
}
|