0

I have two entities which are below :-

  1. Website
  2. Posts

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).

yivi
  • 42,438
  • 18
  • 116
  • 138
Hims V
  • 310
  • 1
  • 9

1 Answers1

1

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.

Stephan Vierkant
  • 9,674
  • 8
  • 61
  • 97
  • As you said according to I have set on the posts entity like cascade={"persist'} but it is not working it is return error like this :- https://nimb.ws/3VZsHv. – Hims V Jul 28 '21 at 06:33
  • I just wanted to keep associate the posts of the deleted website on the database like if we deleted X site from the database but that X website related posts should be kept on the database with null website id on the table something. – Hims V Jul 28 '21 at 06:35
  • Are you sure your database is in sync (check `bin/console doctrine:schema:validate`) and you have your cache cleared? – Stephan Vierkant Jul 28 '21 at 08:56
  • Yes actually I have added join column ORM and set it on delete SET NULL see my screenshot:- https://nimb.ws/nbZHDF and it works in the posts table it will set the website id NULL and that I want to expect the result. BTW thank you...your answer helped me and got a solution. – Hims V Jul 28 '21 at 09:18