Question:How to properly remove an item in a ManyToOne relation
Context:Php 7.3 / Symfony 4 / Doctrine 2.7 / Api-platform 2.5
Description:
I have the following entities:
The Image
class definition
use ApiPlatform\Core\Annotation\ApiResource;use ApiPlatform\Core\Annotation\ApiProperty;use Doctrine\ORM\Mapping as ORM;/** * Class Image * @package App\Entity * * @ApiResource(...) * @ORM\Entity */class Image extends Media{ /** * @ApiProperty() * @ORM\Column(type="guid") * @ORM\Id * @var null|string */ protected $id; /* ... properties */ /* ... getters/setters */}
The Foo
class definition:
use ApiPlatform\Core\Annotation\ApiResource;use ApiPlatform\Core\Annotation\ApiProperty;use Doctrine\ORM\Mapping as ORM;/** * Class Foo * @package App\Entity * * @ApiResource(...) * @ORM\Entity */class Foo{ /** * @ApiProperty() * @ORM\Column(type="guid") * @ORM\Id * @var null|string */ protected $id; /** * @var array|null * @ApiProperty() * @ORM\Mapping\ManyToOne(targetEntity="App\Entity\Image",cascade={"remove"},fetch="EAGER") */ private $image; public function getImage() { return $this->image; } public function setImage($image): void { $this->image = $image; } /* ... other properties */ /* ... getters/setters */}
The Bar
class definition:
class Bar{ /* ... property id */ /** * @var array|null * @ApiProperty() * @ORM\Mapping\ManyToOne(targetEntity="App\Entity\Image",cascade={"remove"},fetch="EAGER") */ private $image; public function getImage() { return $this->image; } public function setImage($image): void { $this->image = $image; } /* ... other properties */ /* ... getters/setters */}
In my current architecture:
- two entities reference the same
Image
entity via an un-idirectionalManyToOne
relation, - a single image may be referenced by several resources
- Two
Foo
instances may have a relation to the sameImage
instance - One
Foo
instance and oneBar
instance may have a relation to the sameImage
instance
- Two
Question/Issue:
In my controller, when I delete a resource (Foo
or Bar
), I want to automatically delete the image (in my database) if none reference are left to this image. how to handle such behavior ?
I try to modify the doctrine annotation in my Foo
(and Bar
) class to trigger the delete cascade :@ORM\Mapping\ManyToOne(targetEntity="App\Entity\Image",cascade={"remove"},fetch="EAGER")
; but in this case, an exception is raised if a reference still exists on the image.
And as the orphanRemoval
flag does not exist on a ManyToOne
relation, I am stuck to identify the right configuration/solution.
Any help is welcome ...