I have two entities which are below :-
In the website entity, I have given OneToMany
relation, And in the posts entity, I have given the ManytoOne
relation.
Website Entity:-
/**
* @var Collection<Post>
*
* @ORM\OneToMany(targetEntity="App\Domain\Entity\Post\Post", mappedBy="website", cascade={"all"})
*/
private Collection $posts;
Post Entity:-
/**
* @ORM\ManyToOne(targetEntity="App\Domain\Entity\Website\Website", inversedBy="posts")
* @ORM\JoinColumn(name="website_id", referencedColumnName="id", onDelete="SET NULL")
*/
private ?Website $website = null;
The issue is that when I deleting a website so relevant all the posts of the website are deleted, but I want to keep the associated posts of the website (which I have deleted website).
You've set cascade={"all"}
on $posts
. all
is an alias for "persist, remove, merge, detach, refresh".
This is what the documentation says about Cascade Operations:
Even though automatic cascading is convenient, it should be used with care. Do not blindly apply cascade=all to all associations as it will unnecessarily degrade the performance of your application.
And, like you just experienced, applying all
makes it harder to understand what's happening when you're working with entities. In your case you might just need persist
:
@ORM\OneToMany(targetEntity="App\Domain\Entity\Post\Post", mappedBy="website", cascade={"persist"})
If you want to learn about cascade operations, this answer will help you a lot.